5

What's the point of the if statement in the following code:

- (NSArray *)myMethod
{
    NSArray *array = nil;
    if (!array) {
        array = [[NSArray alloc] initWithObjects...]
    }
    return array;
}

What's the point of the check if we assigned it to nil and what's the point of assigning it to nil if we didn't put anything inside of it?

1 Answer 1

3

In terms of working code, you are correct, there is no point in checking for nil here. You could rewrite this as:

- (NSArray *)myMethod
{
    return [[NSArray alloc] initWithObjects...]
}

It is hard to know without seeing the entire codebase why this is being done. One possibility is that the original author expected to eventually replace myMethod with a call that potentially passed in a non-nil array or expected to eventually add more complex logic in the allocation.

The other very real possibility (and the most likely one in my opinion) is that whoever wrote it had an ingrained habit of always checking for nil and just wasn't thinking. Since this has no effect on the code, no one ever noticed, or could be bothered to fix.

3
  • I will be using it like this: [[myClass sharedInstance] myMehtod]
    – Jessica
    Jun 16, 2015 at 19:58
  • Would that still be fine?
    – Jessica
    Jun 17, 2015 at 1:03
  • If the local variable was static this would also make a bit more sense.
    – jscs
    Mar 16, 2016 at 20:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.