Search code examples
objective-ciossocketsios5gcdasyncsocket

CocoaAsyncSocket crashes when connecting


I have separated my networking code in a separate class IBStore. The code is very straightforward and based on the samples provided:

#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

and:

#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);
    }
}

This is how IBStore is instantiated from the main view controller:

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

Unfortunately, instead of executing didConnectToHost, the app crashes (hangs) in GCDAsyncSocket.m when it is executing socket4FD = socket(AF_INET, SOCK_STREAM, 0);

Any ideas on why this happens would be highly appreciated. Thank you!


Solution

  • My error was declaring and instantiating the IBStore class in the connect method. Now, I have declared IBStore *client as a instance variable and it works perfect.