Always set NSError pointers to nil, Duh!

This is one of those errors that just make you go, duh!

Can you spot the problem with the following two snippets of code?

Snippet 1

    NSError *error;

    if (![someObject performFetch:&error])

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


Snippet 2


    NSError *error;

    if (![self.someObject performFetch:&error])

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


At first this does not appear to be a problem, but what if someObject is nil in the first case or the accessor self.someObject returns nil in the second?  If either is nil then the message is sent to the nil object which will cause the conditional to fire (a message sent to the nil object returns 0 or nil). Now when error is used it has an uninitialized value, which will probably cause things to blow up, but now always.

The solution to initialize error to nil,

    NSError *error = nil;

    if (![self.someObject performFetch:&error])

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


Or in some cases add a check for the NSError also,

    NSError *error = nil;

    if (![self.someObject performFetch:&error])

        if (error)

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


Always do one of these as the above mistake is simple to make.


smiceli@smiceli.com