Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 768
kizzx2 Avatar asked May 30 '11 14:05

kizzx2


People also ask

How to compare nil in Objective-C?

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.

How do I check if an object is null in Objective-C?

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.

Is nil true in Objective-C?

nil is essentially equal to 0, so those conditions evaluate to to if (0) and if (0 != 0) , both of which are false.

Is nil same as null in C?

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.


2 Answers

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.

like image 100
Itai Ferber Avatar answered Oct 16 '22 20:10

Itai Ferber


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)

like image 34
Vladimir Avatar answered Oct 16 '22 21:10

Vladimir