核心数据的多线程使用(NSOperationQueue 和 NSManagedObjectContext) [英] Multithreaded use of Core Data (NSOperationQueue and NSManagedObjectContext)

查看:16
本文介绍了核心数据的多线程使用(NSOperationQueue 和 NSManagedObjectContext)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Apple 的关于 并发的核心数据文档中使用 Core Data,他们列出了线程安全的首选方法,为每个线程使用单独的 NSManagedObjectContext,并使用共享的 NSPersistentStoreCoordinator.

In Apple's Core Data documentation for Concurrency with Core Data, they list the preferred method for thread safety as using a seperate NSManagedObjectContext per thread, with a shared NSPersistentStoreCoordinator.

如果我在一个 NSOperationQueue 上有多个 NSOperation 一个接一个地运行,那么为每个任务创建上下文会不会有很大的开销?

If I have a number of NSOperations running one after the other on an NSOperationQueue, will there be a large overhead creating the context with each task?

由于 NSOperationQueue 的最大并发操作数为 1,我的许多操作将使用相同的线程.我可以使用线程字典为每个线程创建一个 NSManagedObjectContext 吗?如果我这样做,以后清理上下文会不会有问题?

With the NSOperationQueue having a max concurrent operation count of 1, many of my operations will be using the same thread. Can I use the thread dictionary to create one NSManagedObjectContext per thread? If I do so, will I have problems cleaning up my contexts later?

在这种情况下使用 Core Data 的正确方法是什么?

What’s the correct way to use Core Data in this instance?

推荐答案

在这种情况下使用 Core Data 的正确方法是为每个操作创建一个单独的 NSManagedObjectContext 拥有一个您锁定的上下文(使用前通过 -[NSManagedObjectContext lock] 和使用后-[NSManagedObjectContext unlock]).如果操作是串行的并且没有其他线程使用上下文,则锁定方法可能有意义.

The correct way to use Core Data in this case is to create a separate NSManagedObjectContext per operation or to have a single context which you lock (via -[NSManagedObjectContext lock] before use and -[NSManagedObjectContext unlock] after use). The locked approach might make sense if the operations are serial and there are no other threads using the context.

使用哪种方法是一个经验问题,没有数据就无法回答.变量太多,无法制定一般规则.来自性能测试的硬数据是做出明智决定的唯一途径.

Which approach to use is an empirical question that can't be asnwered without data. There are too many variables to have a general rule. Hard numbers from performance testing are the only way to make an informed decision.

这篇关于核心数据的多线程使用(NSOperationQueue 和 NSManagedObjectContext)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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