[英]Why does this run on main thread?
Very simple code: 很简单的代码:
queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
NSLog(@"%@", [NSThread mainThread]? @"main" : @"not main");
}];
prints "main". 打印“主要”。
Why? 为什么? Isn't it suppose to run in bg thread asynchronously, unless i call
[NSOperationQueue mainQueue]
? 除非我调用
[NSOperationQueue mainQueue]
,否则它不是应该在bg线程中异步运行吗?
[NSThread mainThread]
always returns an object (and thus yielding YES
when cast to BOOL
), since there is a main thread when your program is running. [NSThread mainThread]
始终返回一个对象(因此,当转换为BOOL
时,其结果为YES
),因为程序运行时会有一个主线程。
If you want to check whether the current thread is the main thread or not, you need to use the currentThread
method of NSThread
. 如果要检查当前线程是否为主线程,则需要使用
NSThread
的currentThread
方法。
NSLog(@"%@", [[NSThread currentThread] isEqual:[NSThread mainThread]]
? @"main" : @"not main");
NSThread
has a better method; NSThread
有更好的方法。 it seems you can use the isMainThread
method to check whether the current thread is the main thread or not: 看来可以使用
isMainThread
方法检查当前线程是否为主线程:
if ([[NSThread currentThread] isMainThread]) {
//
}
Well as user @borrrden pointed out, you just need to use [NSThread isMainThread]
, 正如@borrrden用户指出的那样,您只需要使用
[NSThread isMainThread]
,
if([NSThread isMainThread]){
//
}
See the NSThread
documentation . 请参阅
NSThread
文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.