Thursday 14 May 2009

Running iPhone UI code from other than the main thread

If you've got a relatively complex multi-threaded app, where you need to have something happen in the UI in response to an event occuring in a thread that is not the main thread, then you're going to have to be careful!

Basically, what you need to do is use performSelectorOnMainThread to execute your code that does UI work; as otherwise the UI calls you make will probably cause your iPhone app to crash!

The way to do this is to create an instance of an Objective-C++ (or C!) wrapper class that has a method on it which'll do the UI work for you (and could well have a modal loop within it, like for yesterday's post). That method could be something simple, like:


- (void)DoTheUiStuff
{
// All the UI code is here
}


Derive this class from NSObject (or maybe UIView, of course!).

You can then invoke this method through a selector, passed to your call on your class instance to performSelectorOnMainThread. When this call returns, you're safe to clean-up your wrapper class instance and get back to whatever your thread was up to in the first place...

No comments: