0xS*_*ina 2 cocoa-touch objective-c ios
非常简单的代码:
queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
NSLog(@"%@", [NSThread mainThread]? @"main" : @"not main");
}];
Run Code Online (Sandbox Code Playgroud)
打印"主".
为什么?是不是假设在异步运行bg线程,除非我打电话[NSOperationQueue mainQueue]
?
[NSThread mainThread]
总是返回一个对象(因此YES
在转换时会产生BOOL
),因为程序运行时有一个主线程.
如果要检查当前线程是否是主线程,则需要使用currentThread
方法NSThread
.
NSLog(@"%@", [[NSThread currentThread] isEqual:[NSThread mainThread]]
? @"main" : @"not main");
Run Code Online (Sandbox Code Playgroud)
NSThread
有一个更好的方法; 看来你可以使用该isMainThread
方法来检查当前线程是否是主线程:
if ([[NSThread currentThread] isMainThread]) {
//
}
Run Code Online (Sandbox Code Playgroud)
用户@borrrden指出,你只需要使用[NSThread isMainThread]
,
if([NSThread isMainThread]){
//
}
Run Code Online (Sandbox Code Playgroud)
请参阅NSThread
文档.