简体   繁体   English

如何比较两个NSInteger?

[英]How to compare two NSInteger?

How do we compare two NSInteger numbers ? 我们如何比较两个NSInteger数字? I have two NSIntegers and comparing them the regular way wasnt working. 我有两个NSIntegers并比较它们常规方式不起作用。

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

Eventhough, the first value was 13 and the second value was 17, the if loop is executing 尽管如此,第一个值是13,第二个值是17,if循环正在执行

Any idea ? 任何的想法 ?

Well, since you have Integer and Number in the name, you might have declared the two values as NSNumber instead of NSInteger. 好吧,既然你的名字中有Integer和Number,你可能已经将这两个值声明为NSNumber而不是NSInteger。 If so, then you need to do the following: 如果是这样,那么您需要执行以下操作:

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

Otherwise it should work as is! 否则它应该按原样工作!

NSInteger is just a typedef for a builtin integral type (eg int or long ). NSInteger只是内置整数类型的typedef(例如intlong )。

It is safe to compare using a == b . 使用a == b进行比较是安全的。

Other common operators behave predictably: != , <= , < , >= et al. 其他常见的运算符可以预测: !=<=<>=等。

Finally, NSInteger 's underlying type varies by platform/architecture. 最后, NSInteger的底层类型因平台/架构而异。 It is not safe to assume it will always be 32 or 64 bit. 假设它总是32位或64位是不安全的。

NSInteger int1;
NSInteger int2;

int1 = 13;
int2 = 17;

if (int1 > int2)
{
    NSLog(@"works");
}

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);   

}

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

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