计算子 NSDictionary 键

Counting child NSDictionary keys

我正在尝试计算 NSDictionary 字典中字典键的数量,但结果是空的。我要计算的值是字典 SubDict 中的字典有多少个字典,它们在每个字典中 Dict1Dict2Dict3,它们是字典 theDict - 在下面的示例中它应该总计 9。我该如何正确计算儿童词典的键数?

这是我在 NSDictionary 结构中使用的代码。

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

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

它returns值为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;
    };
}; }

如果 theDict 看起来像这样,那么 theDict 中没有 "SubDict" 的键。相反,有四个子字典,每个子字典都有一个子字典。所以你需要累加每个的计数:

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