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!

2

There are 2 answers

0
warrenm On BEST ANSWER

Do not share NSManagedObjectContexts across threads. Do not share NSManagedObjects across threads. There really are no exceptions. Read Concurrency with Core Data and apply the patterns it describes.

0
Farrukh Javeid On

Actually, it is possible and the method that you are looking for is:

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

You have to create a different NSManagedObjectContext for each thread and all you have to do is to put your NSManagedObjectContext in the NSManagedObjectContextDidSaveNotification key in an NSNotification and register it to the default center. On its invokation perform mergeChangesFromContextDidSaveNotification on main thread and your changes will be merged each time you wil invoke the save:&error method.

Note: It has a little demerit, in my opinion, while fetching an object, it may belong to a different context (it will be nil after fetching) and if it does you have to fetch it differently:

NSManagedObjectID *objectID = [YourObject objectID];

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

Hope it helps. Here is a link to better understand what I am saying.