iphone - 循环遍历字典;为什么我不能按字母顺序获取 key ?

标签 iphone objective-c nsmutabledictionary s7graphview

我正在使用 S7Graphview 编写一个 iPhone 应用程序,并且我已将一些日期和结果保存到 .plist 作为字典中的键和值(两者都作为字符串)。我的 plist 如下所示:

<dict>
<key>2011-05-11</key>
<string>23</string>
<key>2011-05-12</key>
<string>23</string>
<key>2011-05-13</key>
<string>23</string>
<key>2011-05-14</key>
<string>43</string>
<key>2011-06-14</key>
<string>43</string>
</dict>

然后我使用这个循环将这些值加载到图形 View 中:

NSMutableDictionary* dictionary = [[NSMutableDictionary alloc]init];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
    dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
int i = 1;        

if ([dictionary count] > 0) {
for (NSString* key in dictionary){
    NSString* verdiString = [dictionary objectForKey:key];
    CGFloat verdi = [verdiString intValue];
    NSDate *dato = [[NSDate alloc]init];
    NSLog(@"key=%@ value=%@", key, [dictionary objectForKey:key]);
    dato = [self stringTilDato:key];
    [items.list_ addObject:[[GraphInfo alloc] initWithID:i name:verdiString value:verdi date:dato]];
    i++;
}
}

“stringTilDato”方法将日期字符串转换为 NSDate。这些值被加载到 items.list 中,但顺序错误! NSLog 报告:

key=2011-05-14 value=43
key=2011-05-13 value=23
key=2011-05-12 value=23
key=2011-06-14 value=43
key=2011-05-11 value=23
key=2011-05-14 value=43
key=2011-05-13 value=23
key=2011-05-12 value=23
key=2011-06-14 value=43
key=2011-05-11 value=23

(顺便说一句,不知道为什么它要经过两次按键,但我不认为这很重要)。我认为按键将按字母顺序读取,或者至少按 plist 的顺序读取。为什么 plist 会按这个顺序加载到字典中,还是我的加载循环有问题?

希望有人可以帮助我:)

最佳答案

字典不是有序的数据结构。您可以假设键没有特定的顺序,并且添加或删除键可以完全更改顺序。如果您需要有序的数据结构,请使用数组,或者在获取所有键后对它们进行排序。

关于iphone - 循环遍历字典;为什么我不能按字母顺序获取 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6347522/

相关文章:

iphone - 应用特定信息 : Application failed to launch in time (iOS)?

objective-c - UISearchBar 搜索包含文本、副文本和图像的表格行

iphone - objective-c int 进行双重计算

uibutton - NSMutableDictionary 以 UIButton* 作为键 - iPhone 开发

xcode - 将可变字典添加到可变字典以转换为 JSON

ios - 如何从给定图像访问 Json 数据

iphone - 关键帧动画期间应用程序崩溃 : -[NSConcreteValue doubleValue] unrecognized selector

iphone - 重置 Game Center 沙盒

ios - 当应用程序从暂停状态返回时隐藏键盘

iphone - 远程写入 .plist 文件 iPhone SDK