0

我已将我的网络代码分隔在一个单独的类 IBStore 中。该代码非常简单,并且基于提供的示例:

#import <UIKit/UIKit.h>
#import "GCDAsyncSocket.h"

@interface IBStore : UIViewController
{
    GCDAsyncSocket *socket;
}
- (void)connect;
- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port;
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag;
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;
@end

和:

#import "IBStore.h"

@interface IBStore ()
@end


@implementation IBStore

- (void)connect
{
    socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];    

    NSError *err = nil;
    if (![socket connectToHost:@"127.0.0.1" onPort:80 error:&err]) // Asynchronous!
    {
        // If there was an error, it's likely something like "already connected" or "no delegate set"
        NSLog(@"Connection error: %@", err);
    }
}

这是从主视图控制器实例化 IBStore 的方式:

- (IBAction)connect:(id)sender {
    IBStore *client = [[IBStore alloc]init];
    [client connect];
}

不幸的是,didConnectToHost应用程序在执行时没有执行,而是在 GCDAsyncSocket.m 中崩溃(挂起)socket4FD = socket(AF_INET, SOCK_STREAM, 0);

任何关于为什么会发生这种情况的想法都将受到高度赞赏。谢谢!

4

1 回答 1

0

我的错误是在方法中声明和实例化 IBStore 类connect。现在,我已将 IBStore *client 声明为实例变量,它运行良好。

于 2012-06-11T15:11:20.817 回答