Search code examples
objective-cnsnumber

NSNumber comparision iOS SDK 4.2 vs 5, in Objective-C?


I found a bug in my app: The logic was that I was comparing two NSNumbers using "==", and I believe it used to work. But it no longer passes on iOS sdk 5, so I need to use isEqualToNumber instead.

Can anyone with iOS sdk 4.2 please try and run the following code and give me the result. I tried to revert to older Xcode to test it myself, but I was not able to do that.

NSNumber *num1 = [NSNumber numberWithInt:100];
NSNumber *num2 = [NSNumber numberWithInt:100];

if (num1 == num2)
{
    NSLog(@"== YES");
}
else
{
    NSLog(@"== NO");
}

Solution

  • The isEqualToNumber is the correct solution here. The fact that it used to work is purely an implementation detail with how the numbers were cached by the system internally. You should never (read probably not what you really want to do) compare objects using ==. == on objects will compare their memory address, not if they're actually equal.