Check key exists in NSDictionary
98,953
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");
Solution 5
Try this:
if ([dict objectForKey:@"bla"]) {
// use obj
} else {
// Do something else like create the object
}
Related videos on Youtube
Comments
-
cocos2dbeginner almost 2 years
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.
-
Admin over 13 yearsAny reason why you’re using
-valueForKey:
instead of-objectForKey:
? The former is used in key-value coding and is slightly slower than the latter.
-
-
kaala over 10 yearsI also wrote the same method in my category, but I have a weird crash happened when I use UIImageWriteToSavedPhotosAlbum(). after narrow down, I change the method name from containsKey => hasKey and the crash disappeared
-
Houman over 10 yearsThis is much better than the accepted answer. I want to search by a key and not if the value of the key is nil or not. You could have a key in a dictionary that points to a nil value. Yet the key exists. The accepted answer doesn't cover this scenario. But this solution here does.
-
Jarno Lamberg over 10 years@Hooman: Not true about a key having a value of nil: the second paragraph of the NSDictionary documentation (developer.apple.com/library/mac/documentation/Cocoa/Reference/…) states that "Neither a key nor a value can be nil; if you need to represent a null value in a dictionary, you should use NSNull." Both this and the accepted answer work for your scenario, i.e. with a dictionary where a value for some key is null (of type NSNull).
-
Palpatim about 10 yearsThis may be a technically correct explanation, but you'll be serving the community better (and likely getting more upvotes) if you provide more detailed discussion about your reasoning in the body of your answer. Why is it appropriate to use
objectForKey:
instead of another method? Why don't you explicitly have to check for a value? At the very least, using the code example provided in the question would make it easier to tie your example to the original question. -
SmileBot almost 10 yearsOr: return [[self allKeys] containsObject:key] ? YES : NO;
-
NiñoScript almost 10 yearswhat's the cast from BOOL to NSNull* for?
-
orion elenzil over 9 yearsgood callout, @Jamo. I'd steer way clear of this answer. my guess is that under the covers, both the call to allKeys and the call to containsObject are each at least O(n), while valueForKey is likely much less.
-
Narasimha Nallamsetty almost 8 yearsFor swift version below code works. let headers:Dictionary = httpResponse .allHeaderFields if (headers["errorcode"] != nil) { print("error key exists ") }
-
Andrei A. over 5 yearsthe value of that key can also be nil therefore this approach will not fully test if a key exists or not in the dictionary
-
Andrei A. over 5 yearsthe value of that key can also be nil therefore this approach will not fully test if a key exists or not in the dictionary
-
John Parker over 5 years@AndreiA.You can't add nil to an NSDictionary.
-
Aaron Ash over 5 years@AndreiA. Neither a key nor a value can be
nil
in an NSDictionary. To represent nil, you can use NSNull. -
fishinear almost 3 yearsThis does not answer the question
-
fishinear almost 3 yearsCasting the pointer to an object to
unsigned long
serves no purpose.