I have a general question about multithreading in iOS:
In my very simple test app, I use NSURLSession to download some small images from the server and present them in a table view. Within the callback of the NSURLSession, after retrieving the images, I call tableview.reloadData() like so:
var session = NSURLSession.sharedSession().dataTaskWithURL(NSURL(url)) {(data, response, error) -> Void in
/* Process images here */
self.tableView.reloadData()
} session.resume()
The images download almost instantaneously, but it takes 10-20 seconds for the table view to update! To be clear, the update delegates aren't even getting called for 10-20 secs. However, if I place reloadData() on the main thread it updates quickly. Like so:
var session = NSURLSession.sharedSession().dataTaskWithURL(NSURL(url)) {(data, response, error) -> Void in
/* Process images here */
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
} session.resume()
So, my problem is solved and I can sleep easy again. But can somebody please explain to me why this is the case? I understand that UI updates should be performed on the main thread - so why does the first case actually still work, yet take FOREVER to do it? There is nothing else going on in the app, so I can't even begin to think what could be holding up the reload for an entire 20 seconds. Is it waiting for the NSURLSession to fully close first, or something along those lines? Finding large prime numbers? Mining Bitcoin?
My knowledge of multithreading is limited, so any insight about this situation would be extremely helpful for future reference.