为什么NSManagedObjectContext队列在主线程上执行? [英] why does NSManagedObjectContext Queue execute on main thread?

查看:53
本文介绍了为什么NSManagedObjectContext队列在主线程上执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我向 NSPrivateQueueConcurrencyType 类型的MOC发送 performBlock 消息时,如下所示:

When I send a performBlock message to my MOC of type NSPrivateQueueConcurrencyType, like this:

[self.privateManagedObjectContext performBlockAndWait:^{
    if ([[NSThread currentThread] isMainThread]) {
        NSLog(@"executing on the main thread!!");        
    }
    …
}];

我发现默认情况下,它在主线程上执行。上面的代码中的条件触发,并且问题导航器指示在 NSManagedObject队列中的线程1 上执行。

I find that, by default, this executes on the main thread. The conditional in the above code triggers, and the Issue Navigator indicates that execution is occurring on Thread 1 in the NSManagedObject Queue.

这对我来说很令人困惑,因为Apple告诉我们每个线程必须具有自己的完全私有的托管对象上下文。假定类型为 NSMainQueueConcurrencyType 的MOC将使用主线程,则它不会违反类型为 NSPrivateQueueConcurrencyType 使用主线程?

This is very puzzling to me, because Apple tells us that "each thread must have its own entirely private managed object context." Given that an MOC of type NSMainQueueConcurrencyType will use the main thread, doesn't it violate thread confinement for an MOC of type NSPrivateQueueConcurrencyType to use the main thread?

在主线程上执行代码是否正常?我是否误解了线程限制?我知道队列不一定与特定线程绑定,但是在这种情况下,私有MOC队列似乎至少应避开主线程(如果没有单个转到线程)。我遇到了一些奇怪的错误,因此我需要弄清楚发生了什么。谢谢!

Is the execution of my code on the main thread normal? Have I misunderstood thread confinement? I understand that a queue is not necessarily tied to a particular thread, but in this case it seems the private MOC queue should at a minimum avoid the main thread, if not have a single go-to thread. I'm having some weird bugs, so I need to figure out what's going on. Thanks!

推荐答案

之所以可以进行优化,是因为 performBlockAndWait:执行了该块
同步,即该方法直到块完成才返回。
因此,该块不会与主线程
上的其他操作并行执行。

This optimization is possible because performBlockAndWait: executes the block synchronously, i.e. the method does not return until the block has finished. Therefore the block will not be executed in parallel with other operations on the main thread.

(出于相同的原因, dispatch_sync(queue,...)可以在主线程
上执行块,而不是在单独的线程上执行。)

(For the same reason, dispatch_sync(queue, ...) may execute a block on the main thread instead of a separate thread.)

这篇关于为什么NSManagedObjectContext队列在主线程上执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆