checking NSError for nil

We’ve all seen this code:

NSError *error;
// do something...
if (error) { // act on error if any, but crashing instead... }

There should be nothing wrong with this code snippet. Except that there can be. I’ve countered many occasions where error was not initialized to nil by default, the if statement was evaluated to true and associated code was executed. But since there was no error, I got runtime errors, many of which were EXC_BAD_ACCESS…

Changing to:

NSError *error = nil;

made my code run fine.

In the literature I’ve read, all variables in Objective-C are initialized to nil, even if not done explicitly. This seems to be not true anymore. Does anyone have an answer to that? Please share in the comments if you do. My theory is because of the new LLVM compiler, but please prove me wrong if I am.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s