In my app I am getting a bunch of SIGABRT crash reports (from specific users) due to this core data save error handling code:
NSError *error = nil;
if (![moc save:&error])
{
if(error)
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
Is there a better way to handle core data save error than terminating the process using abort()?
To save an object with Core Data, you can simply create a new instance of the NSManagedObject subclass and save the managed context. In the code above, we've created a new Person instance and saved it locally using Core Data.
Use Core Data to save your application's permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container.
Still inside the Core Data editor, go to the Editor menu and choose Create NSManagedObject Subclass. Make sure your data model is selected then click Next. Make sure the Commit entity is checked then click Next again.
Based on the fact a save
error should not appear in production my best advice is to follow a similar pattern.
NSError *error = nil;
if ([self.managedObjectContext save:&error] == NO) {
NSAssert(NO, @"Save should not fail");
[self showAlert];
}
- (void)showAlert {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Could Not Save Data"
message:@"There was a problem saving your data but it is not your fault. If you restart the app, you can try again. Please contact support ([email protected]) to notify us of this issue."
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
abort();
}
Credits goes to Matthew Morey as described in NSManagedObjectContext save error.
I really like this approach since it informs the user that something bad happened. In addition to this I will also create a log file that can be sent by email to support. In the log you will put much info as possible to investigate the error. To achieve this, for example, you could use CocoaLumberjack. Take a look also to Mailing Logs by NSSCreenCast.
So Core Data actually provides you with a lot of information about why it couldn't save or why validation failed. You can extract that information and present it to the user in a helpful way and let him/her fix it (in case we are talking about user-generated data). Here's a solution I've come up with: iPhone Core Data "Production" Error Handling
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With