我有一个充满NSDictionary对象的NSArray。每个字典对象都有一个键:值:
颜色:红色
在其他键中......颜色可以是用户生成的多种颜色之一。
我希望能够提取每种颜色并计算每种颜色的数量,所以:
红色:3本词典 黄色:4个字典 等等......这到底有多大可能?只需遍历字典,直到找到一种独特的颜色,然后再次使用NSPredicate搜索该颜色的颜色,冲洗,重复?答案 0 :(得分:2)
您可以维护字典映射颜色到具有该颜色的字典数。例如:
NSMutableDictionary *counts = [NSMutableDictionary dictionary];
for (NSDictionary *dict in myArray) {
NSString *color = [dict objectForKey:@"color"];
NSNumber *val = [counts objectForKey:color];
val = [NSNumber numberWithUnsignedInteger:1+[val unsignedIntegerValue]];
[counts setObject:val forKey:color];
}