Compare a NSNumber to an int

后端 未结 5 2175
长发绾君心
长发绾君心 2021-01-01 17:39

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:@\         


        
5条回答
  •  借酒劲吻你
    2021-01-01 18:24

    You have two problems:

    • You are confusing the NSNumber object with the value it represents.
    • Your 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\"!");
    }
    

提交回复
热议问题