I need to check if an dict has a key or not. How?
if ([MyDictionary objectForKey:MyKey]) {
// "Key Exist"
}
if ([mydict objectForKey:@"mykey"]) {
// key exists.
}
else
{
// ...
}
When using JSON dictionaries:
#define isNull(value) value == nil || [value isKindOfClass:[NSNull class]]
if( isNull( dict[@"my_key"] ) )
{
// do stuff
}
if ([[dictionary allKeys] containsObject:key]) {
// contains key
}
or
if ([dictionary objectForKey:key]) {
// contains object
}
Because nil cannot be stored in Foundation data structures NSNull
is sometimes to represent a nil
. Because NSNull
is a singleton object you can check to see if NSNull
is the value stored in dictionary by using direct pointer comparison:
if ((NSNull *)[user objectForKey:@"myKey"] == [NSNull null]) { }
I'd suggest you store the result of the lookup in a temp variable, test if the temp variable is nil and then use it. That way you don't look the same object up twice:
id obj = [dict objectForKey:@"blah"];
if (obj) {
// use obj
} else {
// Do something else
}