简体   繁体   English

比较NSNumber与固定值?

[英]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. 有没有更好的方法可以将NSNumber与固定值进行比较,感觉有点笨拙。

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

I do know I can use -compare but it pretty much looks the same ... 我知道我可以使用-compare,但是看起来几乎一样...

gary 加里

How about if ([myNumber intValue] == 0) ? 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). NSNumber对象可以包含int,float,doubles等。Ben的方法(与NSNumberintValue )非常快速且易于阅读,但只有在可以保证myNumber始终在int范围内时,它才能正确工作(甚至在将来的代码更改之后也是如此)。

For this reason, your approach is actually superior if you don't know the exact type of myNumber . 因此,如果您不知道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: 另外,如果您尝试使用错误的类型创建NSNumber,则最新版本的Xcode会正确警告您,这可以帮助您尽早发现问题:

Xcode 6.1.3隐式转换警告NSNumber

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM