Check key exists in NSDictionary

how can I check if this exists?:

[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"]

I want to know whether this key exists or not. How can I do that?

Thank you very much :)

EDIT: dataArray has Objects in it. And these objects are NSDictionaries.


Solution 1:

I presume that [dataArray objectAtIndex:indexPathSet.row] is returning an NSDictionary, in which case you can simply check the result of valueForKey against nil.

For example:

if ([[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
    // The key existed...

}
else {
    // No joy...

}

Solution 2:

So I know you already selected an answer, but I found this to be rather useful as a category on NSDictionary. You start getting into efficiency at this point with all these different answers. Meh...6 of 1...

- (BOOL)containsKey: (NSString *)key {
     BOOL retVal = 0;
     NSArray *allKeys = [self allKeys];
     retVal = [allKeys containsObject:key];
     return retVal;
}

Solution 3:

Check if it's nil:

if ([[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
    // SetEntries exists in this dict
} else {
    // No SetEntries in this dict
}

Solution 4:

this also works using Objective-C literals using the following syntax:

NSDictionary *dict = @{ @"key1" : @"value1", @"key2" : @"value2" };
if (dict[@"key2"])
NSLog(@"Exists");
else
NSLog(@"Does not exist");