6

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:

Community
  • 1
  • 1
Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421

3 Answers3

9

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.

Community
  • 1
  • 1
Brad Larson
  • 170,088
  • 45
  • 397
  • 571
  • Bravo, as always +1, thanks Brad Larson. This is the answer I was looking for (without having been able to imagine it). Could you comment on `setNeedsDisplay` and `setNeedsLayout`, and whether you can adjust a string on a `UILabel` safely from another thread? – Dan Rosenstark Dec 16 '11 at 21:57
  • 1
    @Yar - I believe `-setNeedsDisplay` is safe, due to the protections around drawing into a context, but I'm not sure about `-setNeedsLayout`. I believe the latter may not be safe, because that's not dealing with drawing, but instead positioning of views and layers. I think UILabel's text drawing should be safe, but I haven't tested it out myself. – Brad Larson Dec 16 '11 at 22:17
3

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

Duncan Babbage
  • 19,972
  • 4
  • 56
  • 93
0

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]

Mistake78
  • 61
  • 2