Reputation: 12132
I spent some time today chasing down two bugs, and ended up fixing both of them using the same solution.
Now that I have the solution, I was hoping to get some clarity behind it.
I'm comparing an attribute from Core Data (Integer 16/NSNumber) with an Integer (ABPropertyID & ABMultiValueIdentifier).
The bug was in this comparison, and oddly enough, only showed itself after I had killed the app (from the background tray), reopened it, and run through the same process that included the comparison. Anyways...
This is what stopped working after a restart:
if (myNumber.aProperty == [NSNUmber numberWithInt:anInteger]) { /* do stuff here */ }
And these are the two solutions, which so far, are working perfectly:
if ([myNumber.aProperty integerValue] == anInteger) {/* do stuff here */ }
if ([myNumber.aProperty isEqualToNumber:[NSNumber numberWithInt:anInteger]]) { /* do stuff here */ }
To me, they all look identical. I'm always either converting the NSNumber to an integerValue, or converting the integer to an NSNumber.
Any ideas?
Upvotes: 5
Views: 10299
Reputation: 21
netWorkingButtonsIndexes
is the array which holds objects and
LinkedIn
is a number with int
data type.
[[netWorkingButtonsIndexes objectAtIndex:buttonIndex] isEqual:[NSNumber numberWithInteger:LinkedIn]]
By using the isEqual
method we can compare objects with any data rtype.
Upvotes: 1
Reputation: 53950
As you said, both solutions are working...
I would prefer the first one, as it appears more readable, IMHO... It may also be more performant, as you are comparing integers, after having converted a NSNumber to an int.
In the second one, you convert an int to an object, then you compare the two objects... So that's a second method call, which you don't have in the first case...
Hope this helps... : )
Upvotes: 2
Reputation: 723518
Do not use ==
to compare NSNumber
s. Most of the time you'll be comparing two distinct objects, so the comparison won't evaluate to true. If you look at your if condition, notice that you're particularly comparing your property to a brand new NSNumber
object.
Since NSInteger
is a Cocoa wrapper for certain value types, comparing NSInteger
s with ==
works fine.
The implementation of isEqualToNumber:
probably takes the wrapped value types and compares them too.
Upvotes: 11