I’ve got an API returning a JSON encoded string of data that returns a real number or “null” as a value. As long as the JSON contains a numeric or string value, everything works as expected. If the key:value pair value is null, the code below crashes.
How do I properly test NSDictionary objectForKey when it’s getting a NULL from SBJSON?
When the API returns a null for filetype, the code below crashes at the if() line.
My Objective-C code attempts to test for expected values:
if (1 == [[task valueForKey:@"filetype"] integerValue]) {
// do something
} else {
// do something else
}
The API JSON output:
{"tclid":"3","filename":null,"filetype":null}
The NSLog() output of the NSDictionary is:
task {
filename = "<null>";
filetype = "<null>";
tclid = 3;
}
When transferring data from JSON to a Cocoa collection, the
NSNullclass is used to represent “no value”, since Cocoa collections can’t have empty slots.<null>is howNSNullprints itself.To test for this, you can use
someObject == [NSNull null]. It’s a singleton — there’s only one instance ofNSNullper process — so pointer comparison works, although you may prefer to follow the usual Cocoa comparison convention and use[someObject isKindOfClass:[NSNull class]].You’re getting the crash because you’re sending
integerValueto thatNSNullobject.NSNulldoesn’t respond tointegerValueand raises an exception.