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:@\
You have two problems:
NSLog
format string does not match the types of the arguments that you provide.Regarding the first problem: i
is an address, perhaps something like 0x1f84b
. When you test whether i == 0
, you are testing whether i == NULL
. In this case, that means you are testing whether the key "error" was present in the dictionary or not, since looking up a non-existent key garners a NULL
.
[i intValue]
, on the other hand, is an integer. If the NSNumber
contains a value representable as an integer, this will be the value of the NSNumber
. That is what you see when you print the NSNumber
's description using the %@
format specifier.
Regarding the second problem: Comparisons in C and Objective-C return an integer, either 0 (meaning false) or 1 (meaning true). In order to directly print the result of a comparison, you thus need to use the integer format specifier. There are actually two such specifiers, %i
and %d
. You could wrap the result of the comparison in an NSNumber and use %@
to print that, but that's more work than it's worth.
So, here's what you should be doing:
NSNumber *i = [dictionary objectForKey:@"error"];
BOOL haveValue = (i != NULL);
if (haveValue) {
int iValue = [i intValue];
NSLog(@"%d == 0 -> %d", iValue, iValue == 0);
NSLog(@"%@ compared to 0 -> %d", i, [i compare:[NSNumber numberWithInt:0]]);
} else {
NSLog(@"*** Dictionary has no value for key \"error\"!");
}