Reputation: 1942
There are times when you face exception and crash the app. In my case, here:
+ (void)saveContext:(NSManagedObjectContext *)context
{
if ([context hasChanges]) {
[context performBlockAndWait:^{
NSError *error = nil;
BOOL saved = [context save:&error];
if (!saved) {
// do some real error handling
NSLog(@"Could not save master context due to %@", error);
}
else {
if ([context parentContext]) {
[self saveContext:[context parentContext]];
}
}
}];
}
}
It terminated due to save context while migrating Coredata. I don't understand why that piece of code doesn't escape the exception. Shouldn't it log "Could not save master context due to $error"?
Question is, is the NSError has any meaning? How to escape the exception and crash? Should I use @try-catch instead of NSError?
EDIT 1
So, thanks to Mr. TheEye below, I understand that NSError doesn't escape this uncaught exception
, and to avoid the crash, I better use @try-catch instead.
But, "it would be better to correct the cause of the exception, as it should not happen.", so I thought it should be better to update the question as below:
How should I make the context wait until migration done and perform save? In the case of migration failed, I will remove all context and persistent store, so the save process (in case migration failed) should be nullified. Else (migration successful), save normally.
Edit 2
So, to "correct the cause of the exception", I ended up fixed save context like this:
if (context.hasChanges && context.persistentStoreCoordinator.persistentStores.count) {
...
}
And that concluded my issue. Thanks for spending your time here.
Upvotes: 1
Views: 876
Reputation: 9346
The error object only is for expected errors - if something unforeseen happens (eg some threading issue), an exception will be thrown. You can catch it with a try/catch, but it would be better to correct the cause of the exception, as it should not happen.
Upvotes: 1