Is it possible to reuse one shared managed object context beetween threads, when each thread can work with data not related to data in other thread?

StackOverflow https://stackoverflow.com/questions/12812846

Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top