Everyone knows NSOperation is easily the best way to automatically gain powerful multi-threading on iOS/Mac platforms. However, recently for one of my apps, I faced a issue where, the NSURLConnection’s initWithRequest method doesn’t automatically start even if you forcefully send the “start” message.
For example the below code works perfectly on iPhone OS 3.1 and below but fails on iOS 4.
- (void)start
{
[self willChangeValueForKey:@"isExecuting"];
_isExecuting = YES;
[self didChangeValueForKey:@"isExecuting"];
NSURLRequest * request = [NSURLRequest requestWithURL:_url];
_connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
}
Seems like Apple has made a change where in if the NSURLConnection’s initWithRequest method is called from a thread that’s not the main thread, it doesn’t start downloading the URL contents immediately. The bug fix for this issue is fortunately simple.
- (void)start
{
[self willChangeValueForKey:@"isExecuting"];
_isExecuting = YES;
[self didChangeValueForKey:@"isExecuting"];
NSURLRequest * request = [NSURLRequest requestWithURL:_url];
_connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
//iOS 4 bug fix
if (![NSThread isMainThread])
{
[self performSelectorOnMainThread:@selector(start)
withObject:nil waitUntilDone:NO];
return;
}
}
Hope this post solves your problem.
–
Mugunth
Related posts:
- iPhone Tutorial: Follow Cost API and a open source wrapper What is Follow Cost? Follow Cost is a interesting and...

2 Responses to “iOS4 Issue: NSURLConnection and NSOperation”