Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EXC_BAD_ACCESS when calling managedObjectContext save

Occasionally I get this error:

EXC_BAD_ACCESS Code: KERN_INVALID_ADDRESS at 0x13421772123

It happens on the save: line below (in a CoreDataController singleton class)

    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;

    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        }
    }

I know this isn't a lot of code to go from, but from experience is there common cause to this, and any way to prevent this from crashing the app?

like image 421
soleil Avatar asked Sep 26 '13 00:09

soleil


1 Answers

if managedObjectContext is the main context, then you should call it in main thread, try wrap it with following code, incase you call it in a background thread

NSManagedObjectContext *managedObjectContext = self.managedObjectContext;

if (managedObjectContext != nil) {
    [managedObjectContext performBlockAndWait:^{
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        }
    }];
}
like image 58
lanbo Avatar answered Oct 23 '22 03:10

lanbo