连接时CocoaAsyncSocket崩溃

时间:2012-06-08 19:53:55

标签: objective-c ios sockets ios5 gcdasyncsocket

我在单独的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);

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

1 个答案:

答案 0 :(得分:0)

我的错误是在connect方法中声明并实例化IBStore类。现在,我已将IBStore *客户端声明为实例变量,并且工作正常。

相关问题