1

Simple example for the title question: one thread has prepared Place entity and is doing some processing on it (filling particular fields and their calculation takes time) and in the mean time the other thread has already prepared Category entity; the second "Category" thread wants to persist Category entity with save:&error causing Place entity from the first thread to be saved also while it didn't finished its processing job.

Am I right? Will I see the problem described if I use one shared moc?

Thanks!

4

2 回答 2

1

实际上,这是可能的,您正在寻找的方法是:

-(void)mergeChangesFromContextDidSaveNotification:(NSNotification *)notification;

您必须为每个线程创建一个不同NSManagedObjectContext的线程,您所要做的就是将您NSManagedObjectContextNSManagedObjectContextDidSaveNotification密钥放入 anNSNotification并将其注册到默认中心。在主线程上执行它的调用mergeChangesFromContextDidSaveNotification,并且每次调用该save:&error方法时都会合并您的更改。

注意:在我看来,它有一点缺点,在获取对象时,它可能属于不同的上下文(获取后它将为零),如果确实如此,您必须以不同的方式获取它:

NSManagedObjectID *objectID = [YourObject objectID];

YourObject *copy =(YourObject*) [managedObjectContext objectWithID:objectID];

希望能帮助到你。是一个链接,可以更好地理解我在说什么。

于 2012-10-10T06:15:42.557 回答
1

不要NSManagedObjectContext跨线程共享 s。不要NSManagedObject跨线程共享 s。真的没有例外。阅读Concurrency with Core Data并应用它描述的模式。

于 2012-10-10T06:09:13.447 回答