Reputation: 7438
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:
-save
the -backgroundMOCDidSave:
call is not triggered-save
operation on its MOC the notification is triggeredThe 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?
Upvotes: 0
Views: 3865
Reputation: 9006
For now I've noticed one thing that's wrong, but I'm not sure it's causing your error. NSManagedObjectContextDidSaveNotification
is sent on the thread on which MOC that calls save
is running. But merging should be made on the thread MOC merging changes is running on. In your case it works fine if changes are merged from the background to the main MOC, but not the other way around.
Upvotes: 1