15

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 between pointer and integer." How do I fix it?

I come from the Java world, where I'm pretty sure the above statement would fail on compliation.

bpapa
  • 21,409
  • 25
  • 99
  • 147

2 Answers2

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
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
11
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
Frank Krueger
  • 69,552
  • 46
  • 163
  • 208
  • everything does seem to work though, where is a case where this would give me problems? just for some background - "var" is a property in a Domain Object. In one of my ViewControllers, I have a UISegmentedViewController that is used to set the value of "var." So, before the user selects anything, var has not yet been set. – bpapa May 21 '09 at 22:15
  • var == 0 if it has not yet been set –  May 21 '09 at 22:17
  • Sure it has been set - it's been set to an undefined value. ints can *only* take on integral values. You should be comparing against 0 or you should use a separate BOOL flag to determine/designate whether `var` is valid. – Frank Krueger May 21 '09 at 22:18