How do I verify if a key exists on a NSDictionary
?
I know how to verify if it has some content, but I want to very if it is there, because it's dynamic and I have to prevent it. Like in some cases it could happen to have a key with the "name" and is value, but in another cases it could happen that this pair of value don't exists.
The simplest way is:
[dictionary objectForKey:@"key"] != nil
as dictionaries return nil
for non-existant keys (and you cannot therefore store a nil in a dictionary, for that you use NSNull
).
Edit: Answer to comment on Bradley's answer
You further ask:
Is there a way to verify if this: [[[contactDetailsDictionary objectForKey:@"professional"] objectForKey:@"CurrentJob"] objectForKey:@"Role"] exists? Not a single key, because is a really giant dictionary, so it could exist in another category.
In Objective-C you can send a message to nil
, it is not an error and returns nil
, so expanding the simple method above you just write:
[[[contactDetailsDictionary objectForKey:@"professional"]
objectForKey:@"CurrentJob"]
objectForKey:@"Role"] != nil
as if any part of the key-sequence doesn't exist the LHS returns nil
NSDictionary
returns all of the keys as an NSArray
and then use containsObject
on the array.
NSDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"object", @"key"];
if ([[dictionary allKeys] containsObject:@"key"]) {
NSLog(@"'key' exists.");
}
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