我正在尝试遍历 NSMutableDictionary,但我似乎无法得到我想要的。我有一个字典将字符串映射到这样的颜色......
squareColors = [NSMutableDictionary dictionaryWithObjects: [NSMutableArray arrayWithObjects:
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:0],
nil]
forKeys: [NSMutableArray arrayWithObjects:
@"yellow",
@"blue",
@"green",
@"purple",
@"orange",
nil]];
随着时间的推移,每个条目的值(value)都会增加。每隔一段时间我就想查看字典并选择计数最高的颜色。我该怎么做?这是我正在尝试的,但我不熟悉 block 。
__block int mostSquares = 0;
__block NSString* color = @"";
/* Look through the dictionary to find the color with the most number of squares */
[squareColors enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"%@ => %@", key, obj);
NSInteger count = [key integerValue];
if (count > mostSquares)
{
color = key;
mostSquares = count;
}
}];
最佳答案
您的代码中有一个非常简单的错误。这一行:
NSInteger count = [key integerValue];
应该是:
NSInteger count = [obj integerValue];
'key' 是颜色名称,obj
是数字。正如您所拥有的那样,count
每次迭代都会设置为 0
,因为在非数字字符串上调用 integerValue
会给您 0
.
关于ios - 遍历字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14762652/