Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Needs To Be on Main Thread?

Tags:

ios

uikit

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:

  • UIView setNeedsDisplay Not on main thread?
  • Does UIView's -drawRect: have to be called on the main thread?
  • Make UIImage From UIView but NOT in the main thread
like image 223
Dan Rosenstark Avatar asked Dec 16 '11 17:12

Dan Rosenstark


1 Answers

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.

like image 182
Brad Larson Avatar answered Oct 28 '22 00:10

Brad Larson