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 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...