Below is a code block, that is supposed to test to see if a dictionary is null, and if it isn't, pull out the correct object. However, for some reason, despite the fact that the if
check fails, the code still executes. Is there some quirk with how NSNull
works that I don't understand, or is this an Apple bug?
if (svcUser && !(svcUser == (id)[NSNull null])) {
return [svcUser objectForKey:@"access_level"];
}
Console response:
(lldb) print svcUser && !(svcUser == (id)[NSNull null])
(bool) $0 = false
(lldb) continue
-[NSNull objectForKey:]: unrecognized selector sent to instance 0x2b51678
We can use NSNull to represent nil objects in collections, and we typically see NSNull when we convert JSON to Objective-C objects and the JSON contained null values. Our preferred way to check if something is NSNull is [[NSNull null] isEqual:something] .
Nil is for object pointers, NULL is for non pointers, Null and Nil both defined to be equal to the value zero. NULL is a void *, nil is an id, and Nil is a Class pointer, NULL is used for non-object pointer (like a C pointer) in Objective-C.
Simply check for:
svcUser == [NSNull null]
This is the approach that Apple mentions in their docs.
NSNull
is a class. And like with all classes, you must use isEqual:
, not ==
to see if two objects represent the same value.
if (svcUser && ![svcUser isEqual:[NSNull null]]) {
return [svcUser objectForKey:@"access_level"];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With