简体   繁体   中英

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] ?

[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.

If you want to check whether the current thread is the main thread or not, you need to use the currentThread method of NSThread .

NSLog(@"%@", [[NSThread currentThread] isEqual:[NSThread mainThread]] 
      ? @"main" : @"not main");

NSThread has a better method; it seems you can use the isMainThread method to check whether the current thread is the main thread or not:

if ([[NSThread currentThread] isMainThread]) {
   //
}

Well as user @borrrden pointed out, you just need to use [NSThread isMainThread] ,

if([NSThread isMainThread]){
   //
}

See the NSThread documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM