我想就此征询某人的意见。我有一个专用的保存 NSManagedObjectContext
和 GCD 队列,我从中对其进行操作。每当新数据进入我的应用程序时,我都会将其保存在该上下文中,并将更改合并到主上下文中。我的问题出现在告诉主线程刚刚发生了什么。在我调用 save 之后,我的 current 上下文现在是最新的,但是如果我在主上下文中触发一个方法,它的上下文就不是了。如果我等待 NSManagedObjectContextDidSave
通知,并且我保存了三次,我现在有三个排队的委托(delegate)调用,但无法将它们与传入的通知相匹配。有谁知道绕过的好方法这个?
编辑
我最后做的是为每个保存操作创建一个新的上下文,并附加一个 block 以在保存通知到达时调用。看起来像这样,http://pastie.org/2068084
最佳答案
从您对我上面的评论的回答中,我看到您在通知中传递了 managedObjectContext。我对异步的东西还没有那么自信,但我确实认为你违反了一些并发规则,如果我正确地解释了 NSManagedObjectContext Class Reference 中的这句话的话。 :
Concurrency Core Data uses thread (or serialized queue) confinement to protect managed objects and managed object contexts (see “Concurrency with Core Data”). A consequence of this is that a context assumes the default owner is the thread or queue that allocated it—this is determined by the thread that calls its init method. You should not, therefore, initialize a context on one thread then pass it to a different thread. Instead, you should pass a reference to a persistent store coordinator and have the receiving thread/queue create a new context derived from that.
我会说,尝试在通知中传递持久存储协调器并在 block 中重新创建托管对象上下文。
关于objective-c - 为回调匹配 CoreData 保存通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6345079/