开发者

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]]) NS开发者_运维问答Log(@"Zero");

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

gary


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


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:

compare a NSNumber with a fixed value?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜