开发者

Count values in NSDictionarys within an NSArray

I have an NSArray full of NSDictionary objects. Each dictionary object has a key:value:

color: red

Amongst other keys... color could be one of many colors that are user generated.

I would like to be able to extract each color and count how many I have of each, so:

r开发者_如何学Ced: 3 dictionaries yellow: 4 dictionaries

etc... How exactly would this be possible? Just iterate through the dictionaries until you find a unique color, then search the array using NSPredicate again for that color, rinse, repeat?


You could just maintain a dictionary mapping color to the number of dictionaries with that color. For example:

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];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜