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.
Any message to nil will return a result which is the equivalent to 0 for the type requested. Since the 0 for a boolean is NO, that is the result. Show activity on this post. Hope it helps.
The NULL value for Objective-C objects (type id) is nil. While NULL is used for C pointers (type void *). nil = (all lower-case) is a null pointer to an Objective-C object. Nil = (capitalized) is a null pointer to an Objective-C class.
nil is essentially equal to 0, so those conditions evaluate to to if (0) and if (0 != 0) , both of which are false.
They're technically the same thing (0), but nil is usually used for an Objective-C object type, while NULL is used for c-style pointers (void *). Also, NULL is differently defined than nil . nil is defined as (id)0 . NULL isn't.
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.
Both
if (x != nil)
and
if ( x )
are equivalent, so pick the variant that in your opinion makes your code more readable for you (and others who will read and support your code)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With