Reputation: 9767
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
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
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:
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
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