Search code examples
iosobjective-ccore-datarestkitrestkit-0.20

Weird crash using Restkit MainQueueManagedObjectContext - EXC_BAD_ACCESS


Sometimes when I call saveToPersistent on the RestKit MainQueueManagedObjectContext I get the following error and the app crashes.

CoreData: error: Serious application error.  Exception was caught during Core Data change processing.  This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification.  -[UIBarButtonItem controllerWillChangeContent:]: unrecognized selector sent to instance 0x21e70300 with userInfo (null)

[UIBarButtonItem controllerWillChangeContent:]: unrecognized selector sent to instance 0x21e70300 with userInfo (null)

It seems that there are some kind of threading problem.

I save the context via a method like so:

- (BOOL)saveMainContext
{
    __block BOOL contextSaved = NO;
    [[[[CoreDataManager sharedInstance] objectStore] mainQueueManagedObjectContext] performBlockAndWait:^{
        NSError *error = nil;
        if ([[[[CoreDataManager sharedInstance] objectStore] mainQueueManagedObjectContext] saveToPersistentStore:&error]) {
            contextSaved = YES;
        }
    }];

    return contextSaved;
}

It crashes on the saveToPersistent method with EXC_BAD_ACCESS. How can I fix this and what could be the reason for my NSFetchresultscontroller calling a method on a UIBarButtonItem?


Solution

  • Your saveMainContext method should only be called from the main thread and should simply be implemented as:

    - (BOOL)saveMainContext
    {
        NSError *error = nil;
        if ([[[[CoreDataManager sharedInstance] objectStore] mainQueueManagedObjectContext] saveToPersistentStore:&error]) {
            contextSaved = YES;
        } else {
            NSLog(@"Save error: %@", error);
        }
    
        return contextSaved;
    }
    

    Calling an instance of UIBarButtonItem suggests that you have a memory management issue in that something which is observing the context save is not removing itself before it is deallocated. Check all of your observers.