EXTRA EXTRA: Main Thread Gains Exclusive Rights to UI Elements

Table of Content

Read all about it!

Have you ever done this?

//run a background thread
DispatchQueue.global().async { 
    //update the UI
    self.dataLabel.text = "NEW IMPORTANT INFORMATION!!!" 
}

and ended up with this?

=================================================================
Main Thread Checker: UI API called on a background thread: -[UILabel setText:]
PID: 96644, TID: 12264933, Thread name: (none), Queue name: com.apple.root.default-qos, QoS: 0
Backtrace:
...

I had known changing the UI on the main thread was required for a while, but I never really knew why. I had the presence of mind to ask my teacher today, though. The answer was a resounding

Because Apple designed it that way.

Apparently, while there’s no inherent reason for this to be, it’s very common for frameworks to require the modification of UI elements to happen on the primary thread. Logically, there must be something about doing it this way that simplifies things, but there’s really nothing stopping it from happening inherently. As an example that I’ve both never tried, nor do I have any reason to recommend (nor do I recommend against it… I ultimately have no knowledge of it), this framework is ostensibly able to get around the issue.

Why would you want this?

If, for some reason you want a copy of my crashing code, I’ve posted it to the BlogDemo repo.

Leave a Reply

Your email address will not be published. Required fields are marked *