简体   繁体   English

Objective-C中NSNumber的不同值long

[英]different values for NSNumber long in Objective-C

I have a variable which is a NSNumber of type long. 我有一个NSNumber类型为long的变量。 It should hold the value -1. 它应该保持值-1。 When I log it to the Console it shows the expected value -1. 当我将其记录到控制台时,它显示期望值-1。

NSLog(@"myVariable %@", self.myVariable);

But the following expression in the if-clause is false. 但是if子句中的以下表达式为false。

    if (myVariable == [NSNumber numberWithInt:-1]) {
    ...
    }

The debugger shows the value 72057594037927935. Does anybody know what's wrong with it? 调试器显示值72057594037927935。有人知道它出了什么问题吗?

Thanks! 谢谢!

When you compare NSNumber to other objects, you have two options that do different things: NSNumber与其他对象进行比较时,有两个选项可以做不同的事情:

  • You can use == to check if two objects represent the same exact object instance , or 您可以使用==检查两个对象是否代表相同的确切对象实例 ,或者
  • You can use isEqual: method to check if two objects represent the same value . 您可以使用isEqual:方法检查两个对象是否表示相同的

In your case the safest approach would be to use the second alternative 在您的情况下,最安全的方法是使用第二种方法

if ([myVariable isEqual:[NSNumber numberWithLong:-1]]) {
    ...
}

The == approach may or may not work, depending on the way in which you produced myVariable . ==方法可能有效或无效,这取决于生成myVariable

NSObject has a method: (NSString *)description This method will define which is printed out when you put object on NSLog method. NSObject有一个方法:(NSString *)description此方法将定义将对象放在NSLog方法上时打印出的内容。

  • NSNumber inherits NSObject and description method is implemented in the way that primitive value will be printed out, and that's why you saw expected value using NSLog(@"myVariable %@", self.myVariable); NSNumber继承了NSObject并以打印原始值的方式实现了描述方法,这就是为什么您使用NSLog(@"myVariable %@", self.myVariable);看到期望值的原因NSLog(@"myVariable %@", self.myVariable);

  • Operator "==" will compare 2 objects in this case (compare both pointer and value) ==> it will return false in your case 在这种情况下,运算符“ ==”将比较2个对象(比较指针和值)==>在您的情况下它将返回false

  • If you want to compare primitive value of 2 NSNumbers, use following method instead (BOOL)isEqualToNumber:(NSNumber *)number; 如果要比较2个NSNumber的原始值,请改用以下方法(BOOL)isEqualToNumber:(NSNumber *)number;

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

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