fuzzygoat
fuzzygoat

Reputation: 26223

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

Upvotes: 13

Views: 16354

Answers (2)

Andreas Ley
Andreas Ley

Reputation: 9335

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

Upvotes: 5

Ben Gottlieb
Ben Gottlieb

Reputation: 85522

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

Upvotes: 50

Related Questions