Skip to content

Instantly share code, notes, and snippets.

@bentford
Last active December 11, 2015 05:08
Show Gist options
  • Save bentford/4549876 to your computer and use it in GitHub Desktop.
Save bentford/4549876 to your computer and use it in GitHub Desktop.
CoreData: merging changes from background context.
// getting this error?
// "An observer of NSManagedObjectContextDidSaveNotification illegally threw an exception"
// observing the notification here
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(otherContextDidSave:)
name:NSManagedObjectContextDidSaveNotification object:nil];
// FIX: you must mergeChangesFromContextDidSaveNotification: on main thread
// handling the notification occurs on background thread.
// it needs to "merge" on the main thread.
- (void)otherContextDidSave:(NSNotification *)didSaveNotification {
NSManagedObjectContext *context = (NSManagedObjectContext *)didSaveNotification.object;
if( context.persistentStoreCoordinator == globalContext.persistentStoreCoordinator )
[globalContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)
withObject:didSaveNotification waitUntilDone:NO];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment