Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I need to worry about thread-safety in an iOS application?

When writing the usual view controller code, can I assume that this will only be called from a single event-loop thread? What kind of classes do I need to make thread-safe? What are the usual situations where multiple threads are involved?

like image 752
Thilo Avatar asked Aug 18 '11 05:08

Thilo


2 Answers

The concurrency programming guide is good. Here are some super important things to keep in mind.

– You should only update UI from the main thread. This can get you in subtle ways...

– NSNotifications will be received in the thread from which they are fired. So if you launch a thread and subscribe to a NSNotification to trigger a UI action, you should check what thread you're on when you get it. If it's not on the main thread use NSObject's performSelectorOnMainThread: withObject:waitUntilDone: to get it on the main thread.

– If you're doing some drawing into a non-ui context, I believe core graphics is now thread safe. (I believe CATiledLayer does some clever things because of this)

– Generally for view controllers, the only event loop you should think about is the one on the main thread. Think twice before making your own event loop on another thread.

like image 161
David Hodge Avatar answered Nov 12 '22 00:11

David Hodge


If you are writing normal UIViewController code, you don't need to worry about thread-safety in iOS. In iOS, any message about UI should be running on the main thread.

If you don't perform some message in background by you self, normally, you don't have to worry about thread, in most situations, it will always be on the main thread.

P.S. Some Frameworks like Game Kit will some times perform messages in background, but it's not about UI and the document from Apple will warn you to make sure if the message is running on main thread.

like image 31
xuzhe Avatar answered Nov 12 '22 01:11

xuzhe