我正在尝试迭代一个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]];
随着时间的推移,每个条目的价值都会增加。每隔一段时间我就要查看字典并选择计数最多的颜色。我怎么能这样做?这是我正在尝试的,但我不熟悉块。
__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;
}
}];
答案 0 :(得分:3)
您的代码中有一个非常简单的错误。这一行:
NSInteger count = [key integerValue];
应该是:
NSInteger count = [obj integerValue];
'key'是颜色名称,obj
是数字。正如您所知,每次迭代都会count
设置为0
,因为在非数字字符串上调用integerValue
会为您提供0
。
答案 1 :(得分:0)
使用您的示例的简单解决方案:
NSMutableArray *arrayNumbers = [NSMutableArray arrayWithObjects:
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:6],
[NSNumber numberWithInt:4],
nil];
NSMutableArray *arrayColours = [NSMutableArray arrayWithObjects:
@"yellow",
@"blue",
@"green",
@"purple",
@"orange",
nil];
NSMutableDictionary *squareColors = [NSMutableDictionary dictionaryWithObjects:arrayNumbers
forKeys:arrayColours];
NSUInteger indexOfArray = [arrayNumbers indexOfObject:[arrayNumbers valueForKeyPath:@"@max.intValue"]];
NSLog (@"Colour with largest value is %@", [arrayColours objectAtIndex:indexOfArray]);
答案 2 :(得分:0)
您可以将密钥存储到数组中并使用该数组进行迭代吗?这可能是最有效的解决方案,因为无论如何你都需要知道每个键。