ios - 遍历字典

标签 ios objective-c iteration nsdictionary

我正在尝试遍历 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/

相关文章:

ios - 使用带有原型(prototype)单元格的自定义 UITableViewCell

ios - 当我打开文件句柄以供读取时,NSString 如何写入文件?

recursion - Ocaml - 迭代到递归

java - for循环,遍历字母表? java

ios - 谷歌驱动器 API : Insufficient Permission iOS

ios - NSURLSession 后 : difference between uploadTask and dataTask

ios - 将 rangeOfString 从 Objective-c 翻译成 Swift

python - 遍历文件夹,提取不带扩展名的文件名并在 Python 中分配为 API 变量名

ios - 模拟器有问题但设备没有

ios - 苹果是否提供任何媒体传输控件以在我的应用程序中使用