I’m getting an error on a when saving changes to the managed object context, but I have a problem with my error handler: the error is nil, and thus gives me no useful information. I have two versions of the error handler. This one was generated by Xcode, and it works (i.e., the log message contains useful error info):
AppDelegate.c
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil)
{
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
{
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
But I want to be able to pass success/failure (eventually, for now I’m just aborting) + the error information back to the caller, so I have this, which does not work (error is nil, and so provides no useful information about the error).
Database.h
+ (BOOL) commit:(NSError **)error;
Database.c
+ (BOOL) commit:(NSError **)error {
AppDelegate *appDelegate = (AppDelegate*) [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
if (managedObjectContext != nil)
{
if ([managedObjectContext hasChanges] && ![managedObjectContext save:error])
{
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
*/
if (error == nil) {
NSLog(@"Unresolved error");
abort();
} else {
NSLog(@"Unresolved error %@, %@", *error, [*error userInfo]);
abort();
//return FALSE;
}
}
return TRUE;
}
return FALSE;
}
I’m pretty sure my problem is with the pointers, and getting lost in the layers of redirection.
[EDIT:]
The code that calls commit:
[Database commit:nil];
I wonder if I need to add something like this to the start of the commit method, but I’m not sure about the pointers:
if (error == nil) {
error = [[NSError alloc] init];
}
If
commit:is called withnil(from your comment) then this is probably the error. You have to call your function with the address of an error variable:and of course
return NOinstead ofabort()in the error case inside thecommitmethod.There is no need to allocate the error message in your
commitmethod.[managedObjectContext save:error]will do that if the save fails.