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

252,836

Solution 1

objectForKey will return nil if a key doesn't exist.

Solution 2

if ([[dictionary allKeys] containsObject:key]) {
    // contains key
}

or

if ([dictionary objectForKey:key]) {
    // contains object
}

Solution 3

More recent versions of Objective-C and Clang have a modern syntax for this:

if (myDictionary[myKey]) {

}

You do not have to check for equality with nil, because only non-nil Objective-C objects can be stored in dictionaries(or arrays). And all Objective-C objects are truthy values. Even @NO, @0, and [NSNull null] evaluate as true.

Edit: Swift is now a thing.

For Swift you would try something like the following

if let value = myDictionary[myKey] {

}

This syntax will only execute the if block if myKey is in the dict and if it is then the value is stored in the value variable. Note that this works for even falsey values like 0.

Solution 4

if ([mydict objectForKey:@"mykey"]) {
    // key exists.
}
else
{
    // ...
}

Solution 5

When using JSON dictionaries:

#define isNull(value) value == nil || [value isKindOfClass:[NSNull class]]

if( isNull( dict[@"my_key"] ) )
{
    // do stuff
}
Share:
252,836
dontWatchMyProfile
Author by

dontWatchMyProfile

Based in the Czech Republic. Like to swim, like to eat ice cream. The big Cocoa and Cocoa Touch online Training / Session Videos list

Updated on July 08, 2022

Comments

  • dontWatchMyProfile
    dontWatchMyProfile over 1 year

    I need to check if an dict has a key or not. How?