10
Oct
NSOperation and NSURLConnection conflicts
The right way to use NSOperation, NSOperationQueue and NSURLConnection
I stumbled across a problem today when trying to make an asynchronous POST request to a server.
I created a request class by subclassing NSOperation and was calling it by adding it to an NSOperationQueue (more here) and within this class's (void)main method, I was creating an NSURLConnection like this:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]
The problem I was experiencing was none of the NSURLConnection delegate callbacks were being fired.
After a little research I realized that when you create an NSURLConnection using the initWithRequest initialization method, you are creating an asynchronous request. Since I was already in one asynchronous request (the NSOperation), I had created another request that got lost, black-hole like.
To fix it, I simply told NSURLConnection to send the request synchronously:
NSError *error = [[NSError alloc] init]; NSURLResponse *response = [[NSURLResponse alloc] init]; NSData *newData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
After this, everything worked as expected and my operation was still performing everything, including the NSURLConnection asynchronously.
