Why == returns true for NSNumber with the same values?

I usually use isEqualToNumber:NSNumbers to verify equality. You should not work, but it is so, why?

NSNumber *number1 = @5;
NSNumber *number2 = [NSNumber numberWithLong:5];

if (number1 == number2)
{
    NSLog(@"Equal");
}

It should check pointer addresses, not actual values. Has something changed in the compiler?

I am using Xcode 5.1

+4
source share
1 answer

Because they are one and the same object. Instances of small NSNumbers are cached by their implementation, and now Objective-C actually uses tagging for NSNumbers in a specific range.

Similarly, [@"someString" copy]just return @"someString". As long as the semantics are preserved correctly, the structure can do all kinds of things like this under the hood.

+4

Source: https://habr.com/ru/post/1532714/


All Articles