简体   繁体   English

为什么要在主线程上运行?

[英]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 . 如果要检查当前线程是否为主线程,则需要使用NSThreadcurrentThread方法。

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.

相关问题 Closure不会在swift的主线程中运行 - Closure does not run in the main thread in swift 为什么NSManagedObjectContext Queue在主线程上执行? - why does NSManagedObjectContext Queue execute on main thread? 在主线程上运行闭包 - Run closure on main thread NSURLConnection和sendAsynchronousRequest:queue:completionHandler: - 完成块是否在主线程中运行 - NSURLConnection and sendAsynchronousRequest:queue:completionHandler: - does the completion block run in the main thread 当某些东西异步运行时,是否意味着它不在主线程上? - when something is run asynchronously does it mean that it's not on the main thread? 如何在辅助线程上以与主线程相同的速率运行AVAssetReader? - How do I run AVAssetReader at the same rate on a secondary thread as it does on the main thread? 仅在主线程上运行异常 - Only run on the main thread exception 宏在主线程上运行方法 - Macro to run method on main thread 为什么即使在主线程上也需要使用 DispatchQueue.main.async 设置 UIImageView.image - Why does UIImageView.image need to be set using a DispatchQueue.main.async even on the main thread 为什么即使在指定返回 - 后台线程到主线程问题后代码也会执行? - Why does code execute even after specifying return - background thread to main thread issue?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM