Now that we have NSNumber literals with compiler support in Objective-C, is there a preferred way to compare an NSNumber to a known integer value?
The old way is
[myNumber integerValue] == 5
Now we can do [myNumber isEqualToNumber:@5]
or even [myNumber isEqualToNumber:@(someVariable)]
.
Is there an advantage to the isEqualToNumber:
method, or should we stick with integerValue unless the value to compare to is already an NSNumber?
One advantage I can see is if someVariable changes from an NSInteger to a CGFloat, no code changes will be needed for the new way.
The new way is really a new syntax around the old
[myNumber isEqualToNumber:[NSNumber numberWithInt:5]]
which requires an extra call of numberWithInt:
; essentially, we're comparing a solution with a single dispatch and zero allocations to a solution with two dispatches, and possibly an allocation/deallocation.
If you do this comparison outside a tight loop, it wouldn't matter. But if you do it in a really tight loop, perhaps while drawing something, you may see a slowndown. That's why I'd stay with the old method of
[myNumber integerValue] == 5