Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare a NSNumber in an if

How to:

if (myNSNumber == 1)
{
 ...
}

This doesn't seem to build

The object:

like image 413
TheLearner Avatar asked Jan 25 '11 11:01

TheLearner


1 Answers

If myNSNUmber is NSNumber, your code should read,

if ([myNSNumber intValue] == 1) {
    ...
}

If it is NSInteger, you can directly compare it with an integer literal. Because NSInteger is a primitive data type.

if (myNSNumber == 1) {
    ...
}

Note: Make sure you don't have * in your declaration. Your NSInteger declarations should read,

NSInteger myNSNUmber; // RIGHT
NSInteger *myNSNUmber; // WRONG, NSInteger is not a struct, but it is a primitive data type.

The following is based on @BoltClock's answer, which he recently posted here


However if you do need to use a pointer to an NSInteger (that is, NSInteger *) for some reason, then you need to dereference the pointer to get the value:

if (*myNSNUmber == 11) {
}

like image 58
EmptyStack Avatar answered Nov 14 '22 21:11

EmptyStack