Hundley
Hundley

Reputation: 3587

iOS Multithreading - NSURLSession and UI updates

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.

Upvotes: 4

Views: 1426

Answers (1)

michal.ciurus
michal.ciurus

Reputation: 3664

We don't update UI in any thread other than main because it causes deadlocks. What probably happens here is that there's a deadlock for 10-20 seconds and after that time something releases the deadlock.

It's not that updating UI on another thread will always not work. What you experienced is one of many outcomes. We can't really tell what's happening underneath Cocoa so we can't really know.

Just always update your UI on the main thread to avoid strange behavior like that.

https://chritto.wordpress.com/2012/12/20/updating-the-ui-from-another-thread/

Upvotes: 2

Related Questions