Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjectiveC: if (obj) {...} AND if (obj != nil) {...}, which is better?

I've seen a lot of ObjC code which do:

obj = [[SomeObject alloc] init];
if (obj) {
/// ...
}

but as I understood it, the value inside () is a boolean, and 0 indicates FALSE 1 indicates TRUE(there is another case in other language that 0 is true and 1 is false), and if a pointer does not point to anything, it is set to NULL(nil), which is #defined to be 0, so I wonder is it better if I do:

if (obj != nil) {
/// ...
}

as it IS checking if the obj is nil or not, no matter what value nil is, so it does not rely on that nil (or NULL) happen to be defined as 0?

like image 861
hzxu Avatar asked Aug 06 '12 00:08

hzxu


1 Answers

edit: after testing a bit, I have determined that modern compilers will actually create the same machine code for both cases;

orig post:

It is (negligibly, perhaps) more efficient to use

if(obj) {

since you do not need to create the intermediary boolean value (by evaluating the comparison expression). I'm not sure which "other language" you are referring to regarding the non-zero being FALSE; the closest thing I can think of is c programs returning 0 for "success" and anything else for "error". Every modern language I have ever worked with uses 0 as FALSE and any non zero value for TRUE.

In Objective-C, nil is literally 0 (treated like a pointer). It is not just a pointer to zero, it is zero as a pointer. It is therefore reliably equivalent to FALSE (or, in our nomenclature "NO").

edit after testing a bit, I have determined that modern compilers will actually create the same machine code for both cases; probably because nil is essentiall typedef'd to 0, so it knows the two styles of checking are both saying "if this pointer is non-zero".

like image 141
Chris Trahey Avatar answered Nov 09 '22 06:11

Chris Trahey