Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa/Objective-C - Verify if a key exist on a NSDictionary [duplicate]

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.

like image 519
fabio santos Avatar asked Oct 26 '12 16:10

fabio santos


2 Answers

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

like image 54
CRD Avatar answered Oct 25 '22 09:10

CRD


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.");
}
like image 23
Bradley M Handy Avatar answered Oct 25 '22 08:10

Bradley M Handy