I’ve a simple question (I think):
I’m trying to compare a NSNumber with a int, to see if it is 0 or 1. Here is the code:
id i = [dictionary objectForKey:@"error"]; //class = NSCFNumber
NSLog(@"%@ == 0 -> %@", i, i == 0);
NSLog(@"%@ == 0 -> %@", i, [i compare:[NSNumber numberWithBool:NO]]);
I tried this to methods but I get null as result:
2010-10-17 21:57:49.065 Api[15152:a0f] 0 == 0 -> (null)
2010-10-17 21:57:49.065 Api[15152:a0f] 0 == 0 -> (null)
Can you help me?
The result of comparison is a BOOL which is not an Objective-C object. Therefore you should not print it using
%@. Try%dinstead (shows 0 or 1).[a compare:b]returns -1 ifa < b, 0 ifa == band 1 ifa > b. So your 2nd result is expected.You cannot compare an NSNumber directly with an integer. That
i == 0is actually a pointer comparison which checks whetheriis NULL (0), which of course is FALSE if that number exists. So the 1st result is also expected.If you want to check for equality, use
[a isEqualToNumber:b]. Alternatively, you could extract the integer out with[a intValue]and compare with another integer directly.So the followings should work:
If the “number” is in fact a boolean, it’s better to take the
-boolValueinstead.