How do I check if a NSNumber object is nil or empty?
OK nil is easy:
NSNumber *myNumber;
if (myNumber == nil)
doSomething
But if th
NSNumber
is either nil
, or it contains a number, nothing in between. “Emptiness” is a notion that depends on the semantics of the particular object and therefore it makes no sense to look for a general emptiness check.
As for your examples, there are several things going on:
NSMutableDictionary *hash = [NSMutableDictionary dictionary];
[hash setObject:@"" forKey:@"key"];
NSNumber *number = [hash objectForKey:@"key"];
NSLog(@"%i", [number intValue]);
The NSLog
will print 0
here, but only because there’s an intValue
method in NSString
. If you change the message to something that only NSNumber
can do, the code will fail:
NSLog(@"%i", [number unsignedIntValue]);
This will throw:
-[NSCFString unsignedIntValue]: unrecognized selector sent to instance 0x303c
Which means you are not getting some general “empty” value back from the hash, you just get the NSString
you stored there.
When you have an empty (== nil
) NSNumber
and send it a message, the result will be zero. That’s simply a language convention that simplifies code:
(array != nil && [array count] == 0)
(someNumber == nil ? 0 : [someNumber intValue])
Will turn into this:
([array count] == 0)
([someNumber intValue])
Hope this helps.