Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSLog, NSError, bad access

I was doing a rather ordinary addPersistentStore to an NSPersistentStoreCoordinator, and it generated an &error code.

So I went to NSLog it, and got an access error when I did this:

    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

which seems to be the common idiom.

When I reformatted the error statement as follows:

     NSLog(@"Unresolved error   %@",   [error userInfo]);

...the problem went away.

Even NSZombie didn't trap the bad access error correctly!

Any ideas?

like image 630
johnrubythecat Avatar asked Dec 11 '09 17:12

johnrubythecat


1 Answers

How are you catching the error?

The correct way, as described by bbum, is:

NSError *error;
BOOL success = [blah blah:blah error:&error];
if (!success) {
    NSLog(@"Error: %@ %@", error, [error userInfo]); //Or other error handling (e.g., [NSApp presentError:error]).
} else {
    //Succeeded—ignore the error variable entirely
}

(That's for a method blah:error:that returns a BOOL; the example in the question bbum answered was for a method that returned an object. The error-handling pattern is the same for both cases.)

According to his Twitter updates shortly afterward, some APIs will output an error object under the hood even if what you asked for succeeded, which means that testing the error variable instead of the BOOL return can fool you. I think this is what happened to you.

The solution is to only look at the error object if the API reports failure.

like image 118
Peter Hosey Avatar answered Oct 20 '22 00:10

Peter Hosey