Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare a NSNumber to an int

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?

like image 275
patrick Avatar asked Oct 17 '10 20:10

patrick


People also ask

Can you compare Size_t and int?

It is okay to compare a size_t value with an int value, the int value will be implicitly converted to unsigned type. Some compilers will issue a warning when you mix signed and unsigned types in comparisons.

Can you compare long and int in C?

int/long compare always works. The 2 operands are converted to a common type, in this case long and all int can be converted to long with no problems. int ii = ...; long ll = ...; if (ii < ll) doSomethings(); unsigned/long compare always works if long ranges exceeds unsigned .

What is NSNumber in Swift?

NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char , short int , int , long int , long long int , float , or double or as a BOOL .


1 Answers

  1. The result of comparison is a BOOL which is not an Objective-C object. Therefore you should not print it using %@. Try %d instead (shows 0 or 1).

  2. [a compare:b] returns -1 if a < b, 0 if a == b and 1 if a > b. So your 2nd result is expected.

  3. You cannot compare an NSNumber directly with an integer. That i == 0 is actually a pointer comparison which checks whether i is NULL (0), which of course is FALSE if that number exists. So the 1st result is also expected.

  4. 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:

NSLog(@"%@ == 0 -> %d", i, [i isEqualToNumber:[NSNumber numberWithInt:0]]);
NSLog(@"%@ == 0 -> %d", i, [i intValue] == 0);

If the "number" is in fact a boolean, it's better to take the -boolValue instead.

NSLog(@"%@ == 0 -> %d", i, ! [i boolValue]);
like image 143
kennytm Avatar answered Sep 23 '22 07:09

kennytm