johnrubythecat
johnrubythecat

Reputation: 1313

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?

Upvotes: 6

Views: 18158

Answers (2)

vaddieg
vaddieg

Reputation: 626

Do not forget to init NSError with nil value

NSError* err = nil;
[anObject doSomethingGetError:&err];
if (err) {
    NSLog(...);
}

If that does not help, it is API bug

Upvotes: 1

Peter Hosey
Peter Hosey

Reputation: 96373

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.

Upvotes: 18

Related Questions