问题
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?
回答1:
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".
回答2:
0 indicates FALSE 1 indicates TRUE
Close. In C (and Objective-C), a 0 evaluates to false, and a non-zero evaluates to true. So a nil (or NULL) pointer is "false", but any non-nil pointer is "true".
Your examples are essentially equivalent; neither is "better" than the other (unless you or your codebase has a style preference).
来源:https://stackoverflow.com/questions/11821282/objectivec-if-obj-and-if-obj-nil-which-is-better