Dan Rosenstark
Dan Rosenstark

Reputation: 69757

What Needs To Be on Main Thread?

I have written a little define called ensureInMainThread (and I use it quite a bit). However, I'm not sure exactly which user interface methods require being called on the main thread. What about setNeedsDisplay and setNeedsLayout? What is the rule of thumb for methods that need to be called on the main thread in iOS 5.x?

These questions are related (some low quality questions and answers, and some very case specific), but I would like a comprehensive, single good answer:

Upvotes: 6

Views: 3088

Answers (3)

Mistake78
Mistake78

Reputation: 61

With iOS 12, if you call setNeedsDisplay from a background thread, you get the following assert:

Main Thread Checker: UI API called on a background thread: -[UIView setNeedsDisplay]

Upvotes: 0

Brad Larson
Brad Larson

Reputation: 170319

As of iOS 4.0, some user interface updates can be performed on a background thread:

  • Drawing to a graphics context in UIKit is now thread-safe. Specifically:

    • The routines used to access and manipulate the graphics context can now correctly handle contexts residing on different threads.

    • String and image drawing is now thread-safe.

    • Using color and font objects in multiple threads is now safe to do.

David Duncan confirms this in his comments here.

Beyond that, pretty much everything else regarding UIKit is not considered threadsafe, so you should make sure you are interacting with it on the main thread in those cases.

As an aside, I do prefer my block-based implementation of a "always run on the main thread" function over the macro you link to, because I like the explicit wrapping of code that needs to be run on the main thread.

Upvotes: 9

Duncan Babbage
Duncan Babbage

Reputation: 20187

Rule of thumb: Anything that updates the interface must be on the main thread.

Upvotes: 3

Related Questions