I have seen answers aleready posted, they all are talking about...
using objectForKey
method on NSDictionary
, which is not proper if we dont know the key's.
Asked
Active
Viewed 5,038 times
-1

Leo
- 24,596
- 11
- 71
- 92

Vinod Supnekar
- 143
- 1
- 7
-
1How can you check for a particular key-value pair if you don't know the key you're looking for? How will you know if you found it? – rdelmar Jun 09 '15 at 04:52
-
You need to explain your question in more detail. – rob mayoff Jun 09 '15 at 04:53
-
If you want to know, if there is a key you do not know, you can simply use `@voodoo` as key. – Amin Negm-Awad Jun 09 '15 at 05:00
-
if you allocated NSDictinaory ,and then trying to find if it has added with some object,in this case how can you use "objectForKey"? – Vinod Supnekar Jun 09 '15 at 05:01
-
@VinodSupnekar See my answer. – liushuaikobe Jun 09 '15 at 05:04
-
possible duplicate of [How to check if an NSDictionary or NSMutableDictionary contains a key?](http://stackoverflow.com/questions/2784648/how-to-check-if-an-nsdictionary-or-nsmutabledictionary-contains-a-key) – Droppy Jun 09 '15 at 05:14
2 Answers
3
You can use the count
property to test if a NSDictionary
has any entries.
if (aDic.count == 0) {
// aDic is empty.
} else {
// aDic has some entries.
}
And, you can use the objectForKey:
method to test if a specific entry exist.
For example, I want to know if a key named "foo" exist in the dictionary:
if ([aDic objectForKey:@"foo"] != nil) {
// aDic has a entry named "foo"
} else {
// "foo" doesn't exsits
}
Also, you can simplify this:
if (aDic[@"foo"]) {
// aDic has a entry named "foo"
} else {
// "foo" doesn't exsits
}

liushuaikobe
- 2,152
- 1
- 23
- 26
-
yaah...i was thinking about it a while about ..if (aDic.count == 0) {}..and it did the trick...Thank you. – Vinod Supnekar Jun 09 '15 at 05:07
-
@VinodSupnekar Have I explain it clearly? If so, please accept my answer, it's important to me, thanks. – liushuaikobe Jun 09 '15 at 05:08
-
@VinodSupnekar Glad to help. I add some comments to help you understand it better. – liushuaikobe Jun 09 '15 at 05:10
-2
if ([yourDictionary isKindOfClass:[NSDictionary class]])
{
NSLog(@"%@",yourDictionary)
}
-
add some explanation on how this works, otherwise it has very little value – fedorqui Jun 09 '15 at 09:23
-
How would checking if `NSDictionary` is of `NSDictionary` class solve anything. – Popeye Jun 24 '15 at 07:48