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
It's very common (for me at least) to get an object out of a dictionary, expect that it's going to be an NSNumber and then have it return a nil object. If this happens and you do an intValue it will crash.
What I do is setup nil protection because I'd rather get a default value than a crash.
One way is:
-(int) intForDictionary:(NSDictionary *)thisDict objectForKey: (NSString *)thisKey withDefault: (int)defaultValue
{
NSNumber *thisNumber = [thisDict objectForKey:thisKey];
if (thisNumber == nil) {
return defaultValue;
}
return [thisNumber intValue];
}
And I have one just like it for floats. Then you at least get your default value. Another way is to just create a method for nil protection..
-(NSNumber *)nilProtectionForNumber: (NSNumber *)thisNumber withDefault: (NSNumber *)defaultNumber
{
if (thisNumber) {
return thisNumber;
}
else
return defaultNumber;
}
That one you'd call like this:
NSNumber *value = [self nilProtectionForNumber:[dict objectForKey:keyThatShouldBeNSNumber] withDefault:[NSNumber numberWithInt:0]];