Ben Ford

benford.me

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 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];
}