Joel
Joel

Reputation: 1635

GCDAsyncSocket Delegate Calls Not Working

I am having a problem that is the exact same as This problem someone posted on github. GCDAsyncSocket won't connect unless I add

[NSThread sleepForTimeInterval:0.1]

In the last post of the thread this was posted

I think I solved this and as I suspected it was completely my fault. The parent object of the socket was being dealloc'd before the connection was made. If I slept on the thread momentarily the connection was made before dealloc which (I'm just shooting in the dark now) took a retain on my parent object (the delegate).

I don't understand what that means or how to implement that into my code. So far I have tried declaring socket as (retain) and (nonatomic, retain) and (Strong, Nonatomic).

Thanks for taking the time to read my question.

Upvotes: 0

Views: 617

Answers (1)

Siobhán
Siobhán

Reputation: 1452

To rephrase the post you quoted, it's a memory management issue; you need to make sure that the GCDAsyncSocket instance sticks around long enough to make the connection, get a reply from the server, and so on. If you're using a property to transfer ownership of the socket to your own class, then that means that the object that owns the socket also needs to stick around.

Bear in mind that the socket object works asynchronously, so calling -connect isn't a self-contained action that waits for the connection to happen. It just starts the ball rolling on another thread and immediately moves on.

It's hard to say exactly what's going wrong in your case, without seeing the code in question. However, assuming you have something like:

@interface MyController : NSObject
@property (strong, nonatomic) GCDAsyncSocket *socket;
@end

then the most likely culprit is that your MyController instance is getting deallocated prematurely, so you'll want to check your memory management all the way up the ownership chain, making sure your strong references are sticking around as long as you expect them to.

It may help to review Apple's memory management guide, for more detail about how object ownership and the object lifecycle work: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html

Upvotes: 1

Related Questions