Make sure function runs on main thread only

As an alternative to ayoy's method-based GCD implementation for guaranteeing execution on the main thread, I use the following GCD-based function in my code (drawn from another answer of mine):

void runOnMainThreadWithoutDeadlocking(void (^block)(void))
{
    if ([NSThread isMainThread])
    {
        block();
    }
    else
    {
        dispatch_sync(dispatch_get_main_queue(), block);
    }
}

You can then use this helper function anywhere in your code:

runOnMainThreadWithoutDeadlocking(^{
    // Do stuff that needs to be on the main thread
});

This guarantees that the actions taken in the enclosed block will always run on the main thread, no matter which thread calls this. It adds little code and is fairly explicit as to which code needs to be run on the main thread.


I wrote this simple #define which I've been using with great success:

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

That way your method, assuming it's parameterless, looks like this

- (void) updateTheThings {
      ensureInMainThread();
      [self.dog setTailWag:YES];
      // etc...

Alternatively, you can use Grand Central Dispatch API, but it's not very handy:

-(void)updateSomethingOnMainThread {
    void (^doStuff)(void) = ^{
        // stuff to be done
    };

    // this check avoids possible deadlock resulting from
    // calling dispatch_sync() on the same queue as current one
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    if (mainQueue == dispatch_get_current_queue()) {
        // execute code in place
        doStuff();
    } else {
        // dispatch doStuff() to main queue
        dispatch_sync(mainQueue, doStuff);
    }
}

otherwise, if synchronous call isn't needed, you can call dispatch_async() which is much simpler:

-(void)updateSomethingOnMainThread {
    dispatch_async(dispatch_get_main_queue(), ^{
        // do stuff
    });
}

This is fine. You can also use GCD to execute code on the main thread.

Checkout this SO post.

GCD to perform task in main thread