NSLog, NSError, bad access

I did a pretty normal addPersistentStore with NSPersistentStoreCoordinator and it generated an error code.

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

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

which seems to be a common idiom.

When I reformatted the error statement as follows:

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

... the problem has disappeared.

Even NSZombie was not mistaken for a bad access error!

Any ideas?

+6
objective-c cocoa nserror nslog
source share
2 answers

How do you catch a mistake?

The correct way, as described by bbum , is as follows:

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

(This is for the blah:error: method, which returns BOOL , the example in question bbum answered the method that returned the object. The error handling pattern is the same for both cases.)

According to his updates on Twitter shortly afterwards, some APIs will throw an error object under the hood, even if what you asked for , which means that testing a variable error instead of returning BOOL can trick you. I think it happened to you.

The solution is to view the error object only if the API report fails.

+18
source share

Remember to initialize NSError with a null value

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

If this does not help, this is an API error

+1
source share

All Articles