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

后端 未结 2 2029
抹茶落季
抹茶落季 2020-12-11 06:43

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

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

but as I understood it, the value inside () i

相关标签:
2条回答
  • 2020-12-11 07:06

    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".

    0 讨论(0)
  • 2020-12-11 07:28

    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).

    0 讨论(0)
提交回复
热议问题