17

Possible Duplicate:
How to check if an NSDictionary or NSMutableDictionary contains a key?

I can get the an array of the Keys (strings) from the dictionary then loop through it doing a string compare with the Key i want to check for and see if that dictionary contains the key I seek.

But is there a more elegant want to check if the key exists in the dictionary?

        NSArray * keys = [taglistDict allKeys];
        for (NSString *key in keys) 
        {
           // do string compare etc
        }

-Code

Community
  • 1
  • 1

3 Answers3

37

An NSDictionary cannot contain nil values, so you can simply use [NSDictionary objectForKey:] which will return nil if the key does not exist:

BOOL exists = [taglistDict objectForKey:key] != nil;

EDIT: As mentioned by @OMGPOP, this also works using Objective-C literals using the following syntax:

NSDictionary *dict = @{ @"key1" : @"value1", @"key2" : @"value2" };

if (dict[@"key3"])
    NSLog(@"Exists");
else
    NSLog(@"Does not exist");

Prints:

Does not exist
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
10

Trojanfoe is likely better, but you could also do:

[[taglistDict allKeys]containsObject:key]
Eric
  • 4,063
  • 2
  • 27
  • 49
-2

Assuming the key is of type NSString and keys is a dictionary, then you should instead be using something like:

if [keys containObject:key] {
 // do something
}
AlBlue
  • 23,254
  • 14
  • 71
  • 91
MrBr
  • 1,884
  • 2
  • 24
  • 38