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

查看:126
本文介绍了核心数据的多线程使用(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上运行一个接一个的NSOperations之后,是否会有一个大的开销为每个任务创建上下文?

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] code> after use)。如果操作是连续的并且没有其他线程使用上下文,锁定方法可能有意义。

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天全站免登陆