iOS – 为什么我比较两个NSNumbers与“==”工作?

前端之家收集整理的这篇文章主要介绍了iOS – 为什么我比较两个NSNumbers与“==”工作?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的应用程序中,当比较两个NSNumber对象时,我不小心使用了“==”:
NSNumber *number1;
NSNumber *number2;

后来,在这些对象的int值被设置之后,我不小心做到了:

if (number1 == number2) {
    NSLog(@"THEY'RE EQUAL");
}

而且,令人困惑的是,它的工作!我可以发誓我被教导这样做:

if (number1.intValue == number2.intValue) {
    NSLog(@"THEY'RE EQUAL");
}

两个NSNumber对象之间如何使用“==”工作,为什么?这是否意味着以这种方式进行比较呢,还是只是一个侥幸,这通常不能保证每次都能工作?真的让我感到困惑:(

解决方法

这可能是一个侥幸

NSHipster

Two objects may be equal or equivalent to one another,if they share a common set of observable properties. Yet,those two objects may still be thought to be distinct,each with their own identity. In programming,an object’s identity is tied to its memory address.

您的语句可能被评估为YES,因为number1和number2指向同一个对象.如果它们具有相同的值但是两个不同的对象,这将不起作用.

NSNumber变量指向相同的明显原因是您明确地将一个指定给另一个,如下所示:

number1 = number2;

但还有另一件事.从this answer

This is likely either a compiler optimisation or an implementation detail: as NSNumber is immutable there’s no need for them be separate instances. probably an implementation optimisation thinking about it. Likely numberWithInt returns a singleton when called subsequently with the same integer.

但无论如何,最安全的使用isEqualToNumber:,因为没有告诉其他“事情”潜在的深度的代码,可能或可能不会导致它评估是

RyPress

While it’s possible to directly compare NSNumber pointers,the isEqualToNumber: method is a much more robust way to check for equality. It guarantees that two values will compare equal,even if they are stored in different objects.

原文链接:/iOS/336699.html

猜你在找的iOS相关文章