Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 737
cocos2dbeginner Avatar asked Jan 08 '11 17:01

cocos2dbeginner


People also ask

How to check a key is available in NSDictionary?

If you wish to check if the NSDictionary contains any key (non-specific) you should use [dictionary allKeys]. count == 0 If the count is 0 there are no keys in the NSDictionary .

How do I check if a dictionary is null in Objective C?

Sending a message to nil / NULL is always valid in Objective-C. So it depends if you want to check if a dictionary is nil , or if it doesn't have values (as a valid dictionary instance may be empty). In the first case, compare with nil . Otherwise, checks if count is 0, and ensure you're instance is still valid.

What is NSDictionary?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.


3 Answers

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...

}
like image 107
John Parker Avatar answered Oct 08 '22 03:10

John Parker


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;
}
like image 47
Miles Alden Avatar answered Oct 08 '22 03:10

Miles Alden


Check if it's nil:

if ([[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
    // SetEntries exists in this dict
} else {
    // No SetEntries in this dict
}
like image 34
BoltClock Avatar answered Oct 08 '22 04:10

BoltClock