Question

I typically use isEqualToNumber: to check for equality of NSNumbers. The following should not work but it does, why?

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

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

It should be checking the pointer addresses and not the actual values. Did something change in the compiler?

I am using Xcode 5.1

Was it helpful?

Solution

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

Similarly, [@"someString" copy] will simply return @"someString". As long as the semantics are preserved correctly, the framework is free to do all sorts of things like this under the hood.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top