I have a situation where I make some changes to the properties of a NSManagedObject in main thread. It belongs to the main ManagedObjectContext of the app.
My app does has threading enabled which downloads data, each thread has it's own ManagedObjectContext created from the most recent state of a single PersistentStore throughout the application.
I am implementing NSManagedObjectContextDidSaveNotification
so that any changes in the MOC is merged back to the main thread's MOC too. Below is the code for it:
- (void)backgroundMOCDidSave:(NSNotification*)notification
{
// Probable fix for: http://stackoverflow.com/questions/3446983/collection-was-mutated-while-being-enumerated-on-executefetchrequest
if (![NSThread isMainThread])
{
[self performSelectorOnMainThread:@selector(backgroundMOCDidSave:) withObject:notification waitUntilDone:YES];
return;
}
// We merge the background moc changes in the main moc
[self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}
Registering for this notification:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(backgroundMOCDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:nil];
Strange things happen in iOS 7 though. I am accessing a NSManagedObject which is created from the main MOC:
- When I modify a property of the ManagedObject which belongs to main MOC (main thread) and perform a
-save
the-backgroundMOCDidSave:
call is not triggered - When I do not modify any property of the ManagedObject and just perform a
-save
operation on its MOC the notification is triggered
The same code is working perfectly well in iOS 6. Irrespective of whether any changes is done on the ManagedObject or not, when a -save
call is triggered on it's MOC the notification NSManagedObjectContextDidSaveNotification
gets triggered.
Anyone faced this problem before?