ios - 为什么我应该在 main 中为串行队列创建上下文并在 start 中为并发队列创建上下文?

标签 ios core-data concurrency documentation nsoperation

<分区>


想要改进这个问题? 更新问题,以便 editing this post 可以用事实和引用来回答它.

关闭 5 年前

Core Data programming Guide 中有关于线程限制模式 的主题上面写着

You must create the managed context on the thread on which is will be used. If you use NSOperation, note that its init method is invoked on the same thread as the caller. You must not, therefore, create a managed object context for the queue in the queue’s init method, otherwise it is associated with the caller’s thread. Instead, you should create the context in main (for a serial queue) or start (for a concurrent queue).

我只是不明白为什么是这样的?哪里不一样了?

最佳答案

它在您引用的文档中说得很清楚。操作 init 方法在调用者线程上运行,而 main 方法中发生的工作可能在另一个线程上运行。

由于您不能在线程之间共享托管对象上下文,因此您需要在将要使用它的同一线程上创建它。因此,如果您在操作中使用它,则需要确保在运行操作的同一线程上创建上下文。

串行操作在 main 中创建上下文的原因是它们运行默认的 start 实现,而您在实现并发操作时覆盖 start

您可以在 Concurrency Programming Guide 中阅读有关并发操作如何工作的更多信息(提示:搜索“开始”)

关于ios - 为什么我应该在 main 中为串行队列创建上下文并在 start 中为并发队列创建上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11224643/

上一篇:objective-c - 如何使用基类对象定义初始化器来填充基类属性?

下一篇:iphone - 将数据保存在属性列表中

相关文章:

iphone - 在可缩放 ScrollView 中,如何确定窗口中内容的位置?

objective-c - 巨大的核心数据对象

ios - RestKit 0.20 - POST 多个对象

java - Java中的同步函数

java - Java内存模型中局部最终变量的语义?

java - static volatile boolean - 线程没有被终止

ios - 如何找出两个自定义单元格中的哪一个被选中?

ios - 使用 NSUserDefaults 的整数值

ios - Swift 3-使用自定义对象声明NSMutableArray数据类型

swift - 保存到核心数据时 NSFetchedResultsController 不更新