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");
}
halfer
  • 19,824
  • 17
  • 99
  • 186
aryaxt
  • 76,198
  • 92
  • 293
  • 442
  • possible duplicate of [Why NSNumber points to the same address when value are equals?](http://stackoverflow.com/questions/4270121/why-nsnumber-points-to-the-same-address-when-value-are-equals) – Thilo Nov 17 '11 at 03:36
  • 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.2 – aryaxt Nov 17 '11 at 03:38
  • "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. – Thilo Nov 17 '11 at 03:40
  • 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 question – aryaxt Nov 17 '11 at 03:53
  • 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.0 – Joshua Weinberg Nov 17 '11 at 04:42
  • @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 not – aryaxt Nov 17 '11 at 04:48

1 Answers1

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.

Joshua Weinberg
  • 28,598
  • 2
  • 97
  • 90