8

How do we compare two NSInteger numbers ? I have two NSIntegers and comparing them the regular way wasnt working.

if (NSIntegerNumber1 >= NSIntegerNumber2) {
    //do something
}

Eventhough, the first value was 13 and the second value was 17, the if loop is executing

Any idea ?

Ahsan
  • 2,964
  • 11
  • 53
  • 96
  • 1
    That's how you do it. Double-check their values: set a breakpoint right before the `if` and make sure they're what you expect. – jscs Feb 28 '12 at 05:15
  • NSInteger is alis for int. so it should work. Other wise specify the type of NSIntegerNumber1 variable.. – Inder Kumar Rathore Feb 28 '12 at 06:01
  • Are you sure these are NSInteger numbers? My guess is these are NSNumbers and you are trying to compare the pointers. – SVGreg Feb 28 '12 at 12:24
  • 1
    Make sure when you debug you are using p instead of po, thats what fixed my issue – yoshyosh Aug 14 '14 at 18:18
  • Why would p understand types when po does not? If po does not know the type why does it print a seemingly valid value? Whatever the reasons, this helped me find my underlying issue. – owenfi Apr 21 '15 at 11:57

4 Answers4

13

NSInteger is just a typedef for a builtin integral type (e.g. int or long).

It is safe to compare using a == b.

Other common operators behave predictably: !=, <=, <, >= et al.

Finally, NSInteger's underlying type varies by platform/architecture. It is not safe to assume it will always be 32 or 64 bit.

justin
  • 104,054
  • 14
  • 179
  • 226
12

Well, since you have Integer and Number in the name, you might have declared the two values as NSNumber instead of NSInteger. If so, then you need to do the following:

 if ([NSIntegerNumber1 intValue] >= [NSIntegerNumber2 intValue]) {
      // do something
 }

Otherwise it should work as is!

lnafziger
  • 25,760
  • 8
  • 60
  • 101
9
NSInteger int1;
NSInteger int2;

int1 = 13;
int2 = 17;

if (int1 > int2)
{
    NSLog(@"works");
}
Colin Basnett
  • 4,052
  • 2
  • 30
  • 49
Rama Rao
  • 1,043
  • 5
  • 22
2

When comparing integers, using this, would work just fine:

int a = 5;
int b = 7;

if (a < b) {

NSLog(@"%d is smaller than %d" a, b);   

}
wizH
  • 488
  • 2
  • 10