An Observer of NSManagedObjectContext DidSaveNotification Illegally Threw an Exception
Are you getting this error while doing CoreData multi-threading: “An observer of NSManagedObjectContextDidSaveNotification illegally threw an exception”?
I was stuck on this problem, and reading the CoreData docs wasn’t helping. Doing everything in the section “using thread confinement to support concurrency” wasn’t helping.
This error randomly produces exceptions and crashes.
This fix is embarassingly simple:
12345678910111213141516171819
// getting this error?// "An observer of NSManagedObjectContextDidSaveNotification illegally threw an exception"// observing the notification here [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(otherContextDidSave:)name:NSManagedObjectContextDidSaveNotificationobject: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)[globalContextperformSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)withObject:didSaveNotificationwaitUntilDone:NO];}