Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare a NSNumber with a fixed value?

Is there a better way to compare a NSNumber with a fixed value, it just feels a little clunky.

if([myNumber isEqualToNumber:[NSNumber numberWithInt:0]]) NSLog(@"Zero");

I do know I can use -compare but it pretty much looks the same ...

gary

like image 454
fuzzygoat Avatar asked Mar 11 '10 19:03

fuzzygoat


2 Answers

How about if ([myNumber intValue] == 0) ? (or < or >, obviously).

like image 176
Ben Gottlieb Avatar answered Nov 15 '22 18:11

Ben Gottlieb


NSNumber objects can contain ints, float, doubles etc. Ben's approach (comparing to a NSNumber's intValue) is very fast and easy to read, but it only works correctly if you can guarantee that myNumber is always in the range of an int (and always will be, even after future code changes).

For this reason, your approach is actually superior if you don't know the exact type of myNumber.

// This will work regardless if myNumber is an int, double etc.
[myNumber isEqualToNumber:[NSNumber numberWithInt:0]]

If comparing to larger fixed numbers or floats, you'll have to go this route anyway. Also, recent versions of Xcode will properly warn you if you try to create a NSNumber with the wrong type, which can help spot problems early:

Xcode 6.1.3 implicit conversion warning NSNumber

like image 39
Andreas Ley Avatar answered Nov 15 '22 17:11

Andreas Ley