iOS - 为什么它比较两个NSNumbers与“==”? [英] iOS - Why Does It Work When I Compare Two NSNumbers With "=="?

查看:144
本文介绍了iOS - 为什么它比较两个NSNumbers与“==”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,当比较两个 NSNumber 对象时,我不小心使用了==:

In my app, I accidentally used "==" when comparing two NSNumber objects like so:

NSNumber *number1;
NSNumber *number2;

稍后,在这些对象之后 int 值设置,我不小心这样做:

Later on, after these objects' int values were set, I accidentally did this:

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

并且,混淆,它工作!我可以宣誓我被教会这样做:

And, confusingly, it worked! I could have sworn I was taught to do it this way:

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



如何在两个 NSNumber 对象工作,为什么?这是否意味着它可以比较他们的方式,或者它只是一个侥幸,这通常不能保证每次工作?它真的让我迷惑:(

How did using "==" between the two NSNumber objects work, and why? Does that mean it's okay to compare them that way, or was it just a fluke and this is generally not guaranteed to work every time? It really confused me :(

推荐答案

这可能是一个侥幸。

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 指向同一个对象,如果它们具有相同的值,是两个不同的对象。

Its possible that your statement evaluated to YES because number1 and number2 were pointing to the same object. This would not work if they had the same value but were two different objects.

显而易见的原因 NSNumber 变量会指向相同的,如下:

The obvious reason NSNumber variables would point to the same would be that you explicitly assigned one to the other, like so:

number1 = number2;

但还有一个事情。从此答案


这可能是编译器优化或实现细节:因为NSNumber是不可变的,所以它们不需要是单独的实例。可能是一个实现优化思考它。可能的情况下,当以后使用相同的整数调用时,numberWithInt会返回一个单例。

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 :,因为没有告诉其他事情潜藏在代码深度,可能会也可能不会导致它评估 YES

But anyways, its safest to use isEqualToNumber:, as there is no telling what other "things" are lurking in the depths of code that may or may not cause it to evaluate YES

RyPress


虽然可以直接比较NSNumber指针,但isEqualToNumber:检查平等。它保证两个值将相等,即使它们存储在不同的对象中。

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 - 为什么它比较两个NSNumbers与“==”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆