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

情到浓时终转凉″ 提交于 2019-11-30 04:58:10

Primitives can't be nil. nil is reserved for pointers to Objective-C objects. nil is technically a pointer type, and mixing pointers and integers will without a cast will almost always result in a compiler warning, with one exception: it's perfectly ok to implicitly convert the integer 0 to a pointer without a cast.

If you want to distinguish between 0 and "no value", use the NSNumber class:

NSNumber *num = [NSNumber numberWithInt:0];
if(num == nil)  // compare against nil
    ;  // do one thing
else if([num intValue] == 0)  // compare against 0
    ;  // do another thing
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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!