iphoneobjective-ccocoacocoa-touchnull-test

Is if(obj && obj != nil) correct and necessary?


Two parts to this question

1) Is this understanding of what's going on correct?
"if (obj)" is testing to see if the pointer is not 0x0, aka set to an integer memory address
"if (obj != nil)" is comparing the memory address of the object to the memory address of the universal nil object

2) So in a situation where I don't know if a variable is pointing to anything, and if it is, I also don't know if that object is a valid object or nil. I want to do a variety of things based on that information, not just pass a message to obj, which I realize would be safe if it's nil. Is this code both correct and necessary?

if (obj && obj != nil) {
    // Do a bunch of things that should only happen if obj is pointing to a valid object
    [obj someMessage];
    [anotherObj someOtherMessage];
}

Thanks guys!


Solution

  • Correct? Yes. Necessary? No. Objective-C simply #defines nil to (void *)0, which is, in C terms, false. So simply writing

    if (obj) {
        [obj someMessage];
        [anotherObj someOtherMessage];
    }
    

    is sufficient. Further, since Objective-C has message-eating nil, you can simply omit the check in some circumstances. (E.g., if the second line were not there in the if block, you could simply call [obj someMessage] indiscriminately.)