How do I test if a primitive in Objective-C is nil?

前端 未结 2 1222
遇见更好的自我
遇见更好的自我 2020-12-29 07:51

I\'m doing a check in an iPhone application -

int var;
if (var != nil)

It works, but in X-Code this is generating a warning \"comparison b

2条回答
  •  春和景丽
    2020-12-29 08:41

    if (var) {
        ...
    }
    

    Welcome to the wonderful world of C. Any value not equal to the integer 0 or a null pointer is true.

    But you have a bug: ints cannot be null. They're value types just like in Java.

    If you want to "box" the integer, then you need to ask it for its address:

    int can_never_be_null = 42; // int in Java
    int *can_be_null = &can_never_be_null; // Integer in Java
    *can_be_null = 0; // Integer.set or whatever
    can_be_null = 0;  // This is setting "the box" to null,
                      //  NOT setting the integer value
    

提交回复
热议问题