Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing equality to NSNull

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
like image 995
jungziege Avatar asked May 17 '13 02:05

jungziege


People also ask

How do you check NSNull?

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] .

When to use nil vs NULL?

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.


2 Answers

Simply check for:

svcUser == [NSNull null]

This is the approach that Apple mentions in their docs.

like image 195
JE42 Avatar answered Oct 21 '22 11:10

JE42


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"];
}
like image 28
rmaddy Avatar answered Oct 21 '22 13:10

rmaddy