本文介绍了`[NSThread isMainThread]`总是返回YES的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码

dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
      NSLog(@"Main Thread? %d", [NSThread isMainThread]);
});

表明我在主线程中。即使这样做:

shows that I'm in the main thread. Even doing this:

queue = dispatch_queue_create("nonMainQueue", NULL);

仍然报告我在主队列中。这似乎是

still reports that I'm in the main queue. This is, it seems, because I'm using dispatch sync.

这是否意味着我的代码与完全不使用dispatch_sync相同?另外:如果dispatch_sync什么都不做,那又有什么意义呢?

Does this mean that my code is the same as not using dispatch_sync at all? Also: what's the point of dispatch_sync if it does nothing at all, then?

推荐答案

因为队列不是线程,为了检查你是否在主'队列',你必须使用不同的代码,类似于:

Because queues are not threads, in order to check if you are on the main 'queue', you must use different code, something similar to this:

if (dispatch_get_current_queue() == dispatch_get_main_queue()) {
   NSLog(@"On Main Thread!");
}

请注意 dispatch_get_current_queue 已弃用,并且可能会在以后的iOS / Mac OS版本中完全删除。

Just note that dispatch_get_current_queue is deprecated, and is subject to be completely removed in a later iOS/Mac OS version.

这篇关于`[NSThread isMainThread]`总是返回YES的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 20:04