What is the proper way to detect if code is running on the main thread in Objective-C? (iOS)

21,222

[NSThread isMainThread] and, if not, dispatch via any of a number of mechanisms to the main thread (what you have is fine).

Share:
21,222

Related videos on Youtube

Cameron Hotchkies
Author by

Cameron Hotchkies

Updated on November 20, 2020

Comments

  • Cameron Hotchkies
    Cameron Hotchkies over 3 years

    My code needs to guarantee a certain operation run on the main thread, but calls may come from background threads.

    To detect situations in the background I was using the following:

    - (void)selectorToRunInMainThread:(id)arguments
    {
        // push to main thread
            if ([NSRunLoop currentRunLoop] != [NSRunLoop mainRunLoop])
            {
                [self performSelectorOnMainThread:@selector(selectorToRunInMainThread:) withObject:arguments waitUntilDone:NO];
                return;
            }
    
        /*
        ... function content ...
        */
    }
    

    This works on iOS 4 and iOS 3.2 but not on iOS 3.1.3 and earlier. In these earlier versions, the function will keep getting called in an endless loop.

    Changing the comparison to:

    if (![[NSRunLoop currentRunLoop] isEqualTo:[NSRunLoop mainRunLoop]])

    has no effect, they still never compare to the same value.

    I found a solution that appears to be working, but I'd like to see what other people suggest first.

  • Cameron Hotchkies
    Cameron Hotchkies over 13 years
    That's a lot cleaner to read than what I had: if ([[NSRunLoop currentRunLoop] getCFRunLoop] != [[NSRunLoop mainRunLoop] getCFRunLoop])