quantumpotato
quantumpotato

Reputation: 9767

NSDictionary check for null

Is there a quick method for determining if a value is NSNULL in a dictionary without checking for that objects class like

[[dict objectForKey:@"foo"] class] != [NSNull null];

Upvotes: 0

Views: 1518

Answers (3)

jlehr
jlehr

Reputation: 15597

Compare the value, not the class.

dict[@"foo"] == [NSNull null]

The null method returns a singleton instance of NSNull. Since only one instance of NSNull is ever allocated, you can directly compare the instance's address to the addresses of collection elements to determine whether any of them are conceptually null.

Upvotes: 3

Metabble
Metabble

Reputation: 11841

While you can do what ogres says, you should preferably use:

id someObject = [dict objectForKey:@"foo"];
if (someObject != [NSNull null]){
   //do something
}

As [NSNull null] is a singleton and only one of them ever exists, you can perform a direct comparison. This is what is used in the documentation here:

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/NumbersandValues/Articles/Null.html

To test for a null object value, you must therefore make a direct object comparison.

This is the preferred method.

EDIT: This was written before Ogres edited their post to use an identity comparison.

Upvotes: 6

ogres
ogres

Reputation: 3690

Actually what you have posted is not correct , you are comparing class ( NSNull ) to the singleton instance of this class ( NSNull null ) ,

the correct would be

[[dict objectForKey:@"foo"] isKindOfClass:[NSNull class]];

or comparing the instances

[dict objectForKey:@"foo"] == [NSNull null];

but if you have lots of this calls , you can create a category of NSDictionary and add method there , something like

- (BOOL)nl_isNSNullAt:(id)key {
    return [[self objectForKey:key] isKindOfClass:[NSNull class]];
}

or with instances

- (BOOL)nl_isNSNullAt:(id)key {
    return [self objectForKey:key] == [NSNull null];
}

then you can directly access

[dict nl_isNSNullAt:@"foo"]

You can of course choose the name of the method and category ...

Upvotes: 1

Related Questions