Ios 为什么它在主线程上运行?

Ios 为什么它在主线程上运行?,ios,objective-c,cocoa-touch,Ios,Objective C,Cocoa Touch,非常简单的代码: queue = [[NSOperationQueue alloc] init]; [queue addOperationWithBlock:^{ NSLog(@"%@", [NSThread mainThread]? @"main" : @"not main"); }]; 打印“主” 为什么??除非我调用[NSOperationQueue mainQueue],否则它不应该异步运行在bg线程中吗?[NSThread mainThread]总是返回一个对象(因此

非常简单的代码:

queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
    NSLog(@"%@", [NSThread mainThread]? @"main" : @"not main");    
}];
打印“主”


为什么??除非我调用
[NSOperationQueue mainQueue]
,否则它不应该异步运行在bg线程中吗?

[NSThread mainThread]
总是返回一个对象(因此在转换到
BOOL
时会产生
YES
),因为程序运行时有一个主线程

如果要检查当前线程是否为主线程,则需要使用
NSThread
currentThread
方法

NSLog(@"%@", [[NSThread currentThread] isEqual:[NSThread mainThread]] 
      ? @"main" : @"not main");
NSThread
有更好的方法;似乎可以使用
isMainThread
方法检查当前线程是否为主线程:

if ([[NSThread currentThread] isMainThread]) {
   //
}
正如user@borrden指出的,您只需要使用
[NSThread isMainThread]

if([NSThread isMainThread]){
   //
}

请看。

啊……妈的。我认为它返回布尔指示您是否从主线程呼叫。谢谢。@borrrden哎呀。。我怎么会错过呢?你介意我把它加到答案中吗?@Krishnabhadra