NSNumber *number1; NSNumber *number2;
后来,在这些对象的int值被设置之后,我不小心做到了:
if (number1 == number2) { NSLog(@"THEY'RE EQUAL"); }
而且,令人困惑的是,它的工作!我可以发誓我被教导这样做:
if (number1.intValue == number2.intValue) { NSLog(@"THEY'RE EQUAL"); }
两个NSNumber对象之间如何使用“==”工作,为什么?这是否意味着以这种方式进行比较呢,还是只是一个侥幸,这通常不能保证每次都能工作?真的让我感到困惑:(
解决方法
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.