防止 NSManagedObjectContextDidSaveNotification 事件重叠
好吧,我有一个非常棘手的问题,我花了几天时间来理解并且知道我不知道如何解决它。
我有一个从具有不同上下文的不同线程更新的 CoreData 数据库。我的问题是,有时 NSManagedObjectContextDidSaveNotification 事件重叠并导致基础损坏,从而导致崩溃。这是一个示例:
Thread Main NSFetchResultsController
Update database
Save database NSManagedObjectContextDidSaveNotification1
merge delegate process 1
process 1 done
Update database
Save database NSManagedObjectContextDidSaveNotification2
merge delegate process 2
process 2 done
Update database
Save database NSManagedObjectContextDidSaveNotification3
merge delegate process 3
Update database
Save database NSManagedObjectContextDidSaveNotification4
merge
process 3 done
delegate process 4
CRASH
process 4 done
在此伪代码示例中,process1 和 process2 可以正常工作 但有时主线程会收到重叠的更新事件 在 process3 完成之前,process4 开始读取数据库。
有没有官方的办法来处理这个问题? CoreData 是否提供解决方案 对于这种情况还是我必须使用 NSLock ?
谢谢
Ok I have a very tricky problem that I spent days to understand and know I'm not sure how to fix it.
I have a CoreData database updated from different thread with different context. My problem is that sometimes NSManagedObjectContextDidSaveNotification event overlap and create corruption of the base that lead to crash. Here is an example:
Thread Main NSFetchResultsController
Update database
Save database NSManagedObjectContextDidSaveNotification1
merge delegate process 1
process 1 done
Update database
Save database NSManagedObjectContextDidSaveNotification2
merge delegate process 2
process 2 done
Update database
Save database NSManagedObjectContextDidSaveNotification3
merge delegate process 3
Update database
Save database NSManagedObjectContextDidSaveNotification4
merge
process 3 done
delegate process 4
CRASH
process 4 done
In this pseudo code example process1 and process2 works without problem
but sometimes the main thread receives overlapping update event and the
you have process4 starting to read the database before process3 is done.
Is there an official way to deal with that ? Does CoreData offers a solution
to this situation or do I have to use NSLock ?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
上下文应该锁定它们共享的持久存储协调器,以防止这些问题。
如果进程3和进程4都在主线程上运行,那么进程4怎么会在进程3完成之前启动呢?不要忘记通知是在发布通知的线程上收到的,因此您需要显式执行代码以合并主线程上的更改(如果我说的是显而易见的事情,请原谅)。
The contexts should be locking the persistent store coordinator that they share to prevent these issues.
If process 3 and process 4 are running on the main thread, then how can 4 start before 3 is finished? Don't forget that notifications are received on the thread that posts them, so you need explicitly execute your code to merge the changes on the main thread (apologies if I'm stating the obvious).