核心数据 - 在多线程之间共享NSManagedObjects [英] Core Data - sharing NSManagedObjects among multiple threads
问题描述
我遭受了在多个线程中使用单个MOC的所有后果 - 我的应用程序在随机点崩溃,因为MOC是在主线程中创建的,我还使用它在另一个线程中填充DB。
虽然代码是同步的(@synchronize)使用全局单例的应用程序崩溃。
我读到,使用单独的MOC为每个线程将使事情确定,但我还读,它被认为也是一个坏的方法来共享线程的NSManagedObjects。
I suffered all the consequences of using a single MOC in multiple threads - my app crashes at random points because the MOC is created in the main thread and I also use it to fill the DB in another thread. Though the code is synchronized (@synchronize) using a global singleton the app crashes. I read that using a separate MOC for each thread will make things ok but I also read that it is considered also a bad approach to share NSManagedObjects across threads.
我的用例如下:
1)从服务器加载并解析XML,在解析期间,我在数据库中插入每个新的NSManagedObject。这一切发生在一个单独的线程。
2)从主线程,用户与从数据库读取数据的UI交互。
My use case is the following: 1)I load and parse XML from a server and during the parsing I insert each new NSManagedObject in the database. This all happens in a separate thread. 2)From the main thread the user interacts with the UI which reads data from the database.
在这两个线程中,我使用NSManagedObjects。你怎么建议我解决这个问题?我失败多次已经。
In both threads I use NSManagedObjects. How would you suggest me to fix this? I failed multiple times already.
大多数情况下,应用程序创建了错误,表明我正在修改一个集合,枚举它,这是不真实的代码是同步的,而我我重复它没有修改发生,反之亦然 - 而我修改它我不迭代,我保存一旦我完成。
Most often the app creashed with error suggesting that I am modifying a collection while enumerating it which is not true as the code is synchronized and while I am iterating it no modifying happens and vice versa - while I modify it I don't iterate and I save once I am done.
推荐答案
p>每个线程使用一个 NSManagedObjectContext
。如果你在线程之间通信,传递 NSManagedObjectID
,这是线程安全的,并从你的线程上下文中重新获取对象。在我的应用程序中,我有时甚至为每个控制器使用一个上下文。
Use one NSManagedObjectContext
per thread. If you communicate between threads, pass the NSManagedObjectID
, which is thread safe, and fetch the object again from you thread context. In my apps I sometimes even use one context per controller.
要管理不同的上下文,注册 NSManagedObjectContextDidChangeNotification
。在此通知处理中,您可以通过 mergeChangesFromContextDidSaveNotification:
方法将通知传递给每个上下文。此方法是线程保存,并使上下文更新其状态。
To manage the different contexts, register an Observer for the NSManagedObjectContextDidChangeNotification
. Within this notification handling, you pass the notification to each of your contexts via the mergeChangesFromContextDidSaveNotification:
method. This method is thread save and makes the context update its state.
之后,您必须刷新您的视图。如果你有一个基于表视图的应用程序,请查看 NSFetchedResultsController
。这有助于您使用适当的动画自动更新表。如果您不使用表格视图,则必须自己实现UI更新。
After this you have to refresh your views. If you have a table view based application, have a look at NSFetchedResultsController
. This helps you update the table automatically with appropriate animations. If you don't use table views, you have to implement the UI update yourself.
这篇关于核心数据 - 在多线程之间共享NSManagedObjects的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!