Run-loops and threads in Apple's CocoaXMLParser example
In the Co开发者_StackOverflow中文版coaXMLParser class of Apple's CocoaXMLParser example, the following code appears:
rssConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[self performSelectorOnMainThread:@selector(downloadStarted) withObject:nil waitUntilDone:NO];
if (rssConnection != nil) {
do {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
} while (!done);
}
According to the NSRunLoop documentation "In general, your application does not need to either create or explicitly manage NSRunLoop objects. Each NSThread object, including the application’s main thread, has an NSRunLoop object automatically created for it as needed." In the context of this, why is the run-loop explicitly managed in this example? Would it not be created and destroyed automatically by the thread generated by the NSURLConnection request?
In that code, the run loop is basically just being told to run forever, so that that thread can continue to process incoming background data from the NSURLConnection. Even though a run-loop is created for you, by default the thread would terminate when that method ended.
In general when doing something like that it's easier to put everything in an NSOperation which then goes in an NSOperationQueue (although if you are implementing NSUrlConnection callbacks you have to provide a few extra methods in the NSOperation class).
精彩评论