Check whether or not the current thread is the main thread

fish potato picture fish potato · Aug 23, 2010 · Viewed 43.8k times · Source

Is there any way to check whether or not the current thread is the main thread in Objective-C?

I want to do something like this.

  - (void)someMethod
  {
    if (IS_THIS_MAIN_THREAD?) {
      NSLog(@"ok. this is main thread.");
    } else {
      NSLog(@"don't call this method from other thread!");
    }
  }

Answer

rano picture rano · Aug 23, 2010

Have a look at the NSThread API documentation.

There are methods like

- (BOOL)isMainThread

+ (BOOL)isMainThread

and + (NSThread *)mainThread