问题
I'm trying to run a download in a background thread as to not block the main UI thread on iOS, what I did was create a new thread using
[NSThread detachNewThreadSelector:@selector(startDownload) toTarget:downloadObject withObject:nil];
Then the following code runs on a background thread:
NSURL* urlForCalendar = [NSURL URLWithString:@"http://www.apple.com/"];
urlRequest = [NSURLRequest requestWithURL:urlForCalendar];
urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:NO];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[urlConnection scheduleInRunLoop:runLoop forMode:NSRunLoopCommonModes];
[urlConnection start];
However, the delegate callbacks are never called.
EDIT: For anyone who might come across a similar problem in the future, after a bit of trying to figure out why it wasn't working, I wasn't running the loop. So the last 3 lines of code should actually be:
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[urlConnection scheduleInRunLoop:runLoop forMode:NSRunLoopCommonModes];
[urlConnection start];
[runLoop run];
回答1:
You don't run the run loop of the thread you created, so the connection you add to the run loop is never serviced and you never get any callbacks.
Generally you just want to handle the callbacks on the main thread and then push the result to a background thread if heavy processing is required.
You can do what you're currently doing though so long as you run the run loop and tidy up properly once the download is complete.
来源:https://stackoverflow.com/questions/25023644/nsurlconnectiondelegate-methods-not-called-when-using-nsthread