Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 404
bpapa Avatar asked May 21 '09 22:05

bpapa


People also ask

How do I check if an object is nil in Objective-C?

Any message to nil will return a result which is the equivalent to 0 for the type requested. Since the 0 for a boolean is NO, that is the result. Show activity on this post. Hope it helps.

What is nil in Objective-C?

Objective-C builds on C's representation of nothing by adding nil . nil is an object pointer to nothing. Although semantically distinct from NULL , they are technically equivalent.

Can bool be nil Objective-C?

You can't. A BOOL is either YES or NO . There is no other state.

What is nil value in C?

In computer programming, null is both a value and a pointer. Null is a built-in constant that has a value of zero. It is the same as the character 0 used to terminate strings in C. Null can also be the value of a pointer, which is the same as zero unless the CPU supports a special bit pattern for a null pointer.


1 Answers

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
like image 95
Adam Rosenfield Avatar answered Sep 28 '22 04:09

Adam Rosenfield