I have recently been learning the Apple SDK (for iPhone, etc) and came across something I can't understand. In the docs for "Using NSURLConnection" from http://developer.apple.com/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
I found a strange piece of explanation and example code. First, it says:
The download starts immediately upon receiving the initWithRequest:delegate: message. It can be canceled any time before the delegate receives a connectionDidFinishLoading: or connection:didFailWithError: message by sending the connection a cancel message.
Next, it shows the following piece of code:
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if (theConnection) { // Create the NSMutableData that will hold // the received data // receivedData is declared as a method instance elsewhere receivedData=[[NSMutableData data] retain]; } else { // inform the user that the download could not be made }
So, it seems to me that the download must start immediately in a different thread as soon as theConnection is initialized. This is clear because the code is non blocking and sends back messages to the delegate, in this case, self. Yet, the (autorelease style) allocation of receivedData happens after the other thread is started. Isn't this an unsafe race condition? Couldn't this result in a crash, memory leak, or loss of data in the event of a very fast server response (e.g. over loopback device) or in the case of unlucky thread scheduling? Wouldn't it make more sense to allocate receivedData before theConnection is initialized, and then just release it in the else case above?
I am so confused by this piece of code, hope somebody can shed some light on it for me. Thanks for any info,
Rudi Cilibrasi