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

前端 未结 2 1224
遇见更好的自我
遇见更好的自我 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:37

    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
    

提交回复
热议问题