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

1

0

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");
}
Ligan answered 17/11, 2011 at 3:34 Comment(6)
possible duplicate of Why NSNumber points to the same address when value are equals?Koons
not a duplicate, I am not asking for the answer I know that the answer is equalsToNumber. I asked if someone could tell me what the result is on iOS 4.2Ligan
"I believe it used to work": According to the question linked above, numbers from 0 to 12 get the same NSNumber instance singleton. But you should not depend on that.Koons
That doesn't help, Like I mentioned in the question I need to know what the behavior is on iOS 4.2. I don't know how I can be any more clear. the NSNumbers I was using were auto-increment numbers in the database mostly 6-7 digits, so the question linked does not answer my questionLigan
The problem is that if this behavior working in 4.2 is completely inconsequential. It is not something that should EVER be relied upon. You had a bug under 4.2 that was exposed in 5.0Antrum
@JoshuaWeinberg I totally agree with you and I'm going to fix this problem regardless of what the result would be on 4.2. The problem is that my application is a web-service based application and my guess is based on the logs on the server side. I want to confirm that the bug only exists on iOS 5 that way, I can stop looking for the problem, and submit a new version with the fix as soon as possible. I am still trying to install 4.2 on my computer to confirm this. I really need to know whether the following code passes on 4.2 or notLigan
A
6

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.

Antrum answered 17/11, 2011 at 3:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.