iPhone Core Data “Production” Error Handling

前端 未结 5 1116
陌清茗
陌清茗 2020-12-04 05:52

I\'ve seen in the example code supplied by Apple references to how you should handle Core Data errors. I.e:

NSError *error = nil;
if (![context save:&err         


        
5条回答
  •  春和景丽
    2020-12-04 06:23

    I found this common save function a much better solution:

    - (BOOL)saveContext {
        NSError *error;
        if (![self.managedObjectContext save:&error]) {
            DDLogError(@"[%@::%@] Whoops, couldn't save managed object context due to errors. Rolling back. Error: %@\n\n", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error);
            [self.managedObjectContext rollback];
            return NO;
        }
        return YES;
    }
    

    Whenever a save fails this will rollback your NSManagedObjectContext meaning it will reset all changes that have been performed in the context since the last save. So you have to watch out carefully to always persist changes using the above save function as early and regularly as possible since you might easily lose data otherwise.

    For inserting data this might be a looser variant allowing other changes to live on:

    - (BOOL)saveContext {
        NSError *error;
        if (![self.managedObjectContext save:&error]) {
            DDLogError(@"[%@::%@] Whoops, couldn't save. Removing erroneous object from context. Error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), object.objectId, error);
            [self.managedObjectContext deleteObject:object];
            return NO;
        }
        return YES;
    }
    

    Note: I am using CocoaLumberjack for logging here.

    Any comment on how to improve this is more then welcome!

    BR Chris

提交回复
热议问题