检查当前线程是否是主线程

fis*_*ato 117 iphone cocoa multithreading objective-c xamarin.ios

有没有办法检查当前线程是否是Objective-C中的主线程?

我想做这样的事情.

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

ran*_*ano 159

看看NSThreadAPI文档.

有像这样的方法

- (BOOL)isMainThread

+ (BOOL)isMainThread

+ (NSThread *)mainThread


boh*_*rna 23

如果要在主线程上执行方法,可以:

- (void)someMethod
{
    dispatch_block_t block = ^{
        // Code for the method goes here
    };

    if ([NSThread isMainThread])
    {
        block();
    }
    else
    {
        dispatch_async(dispatch_get_main_queue(), block);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 旧问题的答案可以从新答案与现有答案的不同之处得到解释. (4认同)
  • @Eric我同意,但是如果你想要在主线程中已经立即执行该方法怎么办?在您的建议中,始终调度该方法以便稍后通过主操作队列执行. (3认同)

dim*_*mdy 19

在Swift3中

if Thread.isMainThread {
    print("Main Thread")
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*ric 12

如果你想知道你是否在主线程上,你可以简单地使用调试器.在您感兴趣的行设置断点,当程序到达时,请调用:

(lldb) thread info

这将显示有关您所在线程的信息:

(lldb) thread info thread #1: tid = 0xe8ad0, 0x00000001083515a0 MyApp`MyApp.ViewController.sliderMoved (sender=0x00007fd221486340, self=0x00007fd22161c1a0)(ObjectiveC.UISlider) -> () + 112 at ViewController.swift:20, queue = 'com.apple.main-thread', stop reason = breakpoint 2.1

如果是的值queuecom.apple.main-thread,那么你在主线程上.


T.J*_*.J. 6

以下模式将确保在主线程上执行方法:

- (void)yourMethod {
    // make sure this runs on the main thread 
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:_cmd/*@selector(yourMethod)*/
                               withObject:nil
                            waitUntilDone:YES];
        return;
    }
    // put your code for yourMethod here
}
Run Code Online (Sandbox Code Playgroud)