-1

my questions is about iPhone development.

I'm trying to figure out if there is a way to count ONLY the number of dictionaries within a dictionary.

for example, let's say this is my dictionary

Dictionary contains 5 elements:

  1. string
  2. string
  3. NSDictionary
  4. NSDictionary
  5. NSDictionary

I would like to count only the NSDictionaries... so the return value should be 3.

Is there any way to accomplish this?

Thanks.

4 Answers 4

4
NSSet *dictKeys = [myDict keysOfEntriesPassingTest:^(id key, id obj, BOOL *stop) {
    return [obj isKindOfClass:[NSDictionary class]];
}];
NSUInteger numberOfDicts = [dictKeys count];
0
1
NSDictionary* root = ...;

__block NSUInteger count = 0;
[root enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL* stop) {
    if ( [obj isKindOfClass: NSDictionary.class] ) ++ count;
    *stop = NO;
}];

Of course

NSUInteger count = 0;
for (id obj in root) {
    if ( [obj isKindOfClass: NSDictionary.class] ) ++ count;
}

will work as well.

1
__block NSInteger countOfDictionaries = 0;

[dictionary enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))block             {
    if ([obj isKindOfClass:[NSDictionary class]]) {
          countOfDictionaries++;
    }
}];

As shown above, simply enumerate through every object of your dictionary and keep a count of every object that is an "NSDictionary", by testing the class of the object.

0

Loop through your NSDictionary by using NSEnumrator and do the following test :

if ([myObject class] == [NSDictionary class]) c++;

1
  • 1
    Ouch, this is like begging for errors! Especially when dealing with class clusters like NSDictionary.
    – JustSid
    Jun 22, 2012 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.