Reputation: 21563
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]
?
Upvotes: 2
Views: 305
Reputation: 34285
[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.
Upvotes: 6