NSLog, NSError, bad access

johnrubythecat picture johnrubythecat · Dec 11, 2009 · Viewed 16.1k times · Source

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?

Answer

Peter Hosey picture Peter Hosey · Dec 11, 2009

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.