Jack Bauer
Jack Bauer

Reputation: 45

Counting child NSDictionary keys

I'm trying to count the number of dictionary keys within an NSDictionary dictionary's dictionary but am coming up empty. The values I would like to count are how many dictionaries are in those of the dictionary SubDict, which are in each dictionary Dict1, Dict2, Dict3, which are part of dictionary theDict - in the example below it should total 9. How would I properly count the children's children dictionary's keys?

Here's the code I've used with the NSDictionary structure.

NSDictionary *keyCount = [theDict objectForKey:@"SubDict"];
NSUInteger count = [[keyCount allKeys] count];

NSLog(@"%lu", (unsigned long) count);

It returns the value 0.

Dict1 =     {
    SubDict =         {
        1 = data;
        2 = data;
        3 = data;
        4 = data;
    };
};
Dict2 =     {
    SubDict =         {
        1 = data;
        2 = data;
    };
};
Dict3 =     {
    SubDict =         {
        1 = data;
        2 = data;
        3 = data;
    };
}; }

Upvotes: 0

Views: 181

Answers (1)

Ben Zotto
Ben Zotto

Reputation: 71048

If theDict looks like this, then there is no key in theDict for "SubDict". Instead there are four child dictionaries, each of which has one child. So you need to accumulate the count of each one:

int count = 0;
for (NSDictionary * dict in theDict.allValues) {
    count += [[dict objectForKey:"SubDict"] count];
}
NSLog(@"total items: %d", count);

Upvotes: 2

Related Questions