Search code examples
objective-csyntax

Testing for nil in Objective-C -- if(x != nil) vs if(x)


Most of the examples I found on the net write this:

if(x != nil)
    // ...

Is there any problems with this?

if(x)
    // ...

I tried both in a simple program and couldn't found any difference.


Solution

  • In Objective-C, nil is defined as a value called __DARWIN_NULL, which essentially evaluates to 0 or false in if-statements. Therefore, writing if (x == nil) is the same as writing if (!x) and writing if (x != nil) is equal to if (x) (since comparing to false creates a negation, and comparing to true keeps the condition the same).


    You can write your code either way, and it really depends on which you think is more readable. I find if (x) to make more sense, but it depends on your style.

    It's like comparing if (someCondition == true) versus if (someCondition).
    It all depends on you, and who's going to be reading the code.


    Edit: As Yuji correctly mentions, since Objective-C is a superset of C, any condition that evaluates to a value other than 0 is considered to be true, and therefore, if someCondition in the example above were to evaluate to an integer value of, say, -1, comparing it to true would result in false, and the if-statement would not be evaluated. Something to be aware of.