Wednesday, October 19, 2011

Ensure in Main Thread

Multithreaded programming is a must in iOS. If you schedule an NSTimer and yet it doesn't fire, it might be because the thread that launched it is now dead. If it's related to UI, you'll need to get to the main thread eventually, anyway. Use this

#define ensureInMainThread(); if ([NSThread currentThread] != [NSThread mainThread]) { [self performSelectorOnMainThread:_cmd withObject:nil waitUntilDone:NO];    return; } 

It can only be used from methods that accept (and return) no parameters.

Now you can have pretty code like this

- (void) msgReceived {


Beware that using code like this might indicate that you are completely lost in a sea of threads. If you have no idea why you need this method, you should go back to your code and figure it out.

No comments: