Reputation: 15
I have a variable which is a NSNumber of type long. It should hold the value -1. When I log it to the Console it shows the expected value -1.
NSLog(@"myVariable %@", self.myVariable);
But the following expression in the if-clause is false.
if (myVariable == [NSNumber numberWithInt:-1]) {
...
}
The debugger shows the value 72057594037927935. Does anybody know what's wrong with it?
Thanks!
Upvotes: 0
Views: 689
Reputation: 440
NSObject has a method: (NSString *)description This method will define which is printed out when you put object on NSLog method.
NSNumber inherits NSObject and description method is implemented in the way that primitive value will be printed out, and that's why you saw expected value using NSLog(@"myVariable %@", self.myVariable);
Operator "==" will compare 2 objects in this case (compare both pointer and value) ==> it will return false in your case
If you want to compare primitive value of 2 NSNumbers, use following method instead (BOOL)isEqualToNumber:(NSNumber *)number;
Upvotes: 1
Reputation: 726589
When you compare NSNumber
to other objects, you have two options that do different things:
==
to check if two objects represent the same exact object instance, orisEqual:
method to check if two objects represent the same value.In your case the safest approach would be to use the second alternative
if ([myVariable isEqual:[NSNumber numberWithLong:-1]]) {
...
}
The ==
approach may or may not work, depending on the way in which you produced myVariable
.
Upvotes: 1