【发布时间】:2013-04-27 11:30:59
【问题描述】:
如何控制字典或 plist 中项目的迭代顺序?
我有一个包含 65 个项目的 plist。每个项目都是一个字典,其中包含三个项目、一个数字(索引)和两个作为图像名称的字符串。 plist 看起来像这样:
<key>Item 1</key>
<dict>
<key>index</key>
<integer>0</integer>
<key>thumb</key>
<string>001_item01.png</string>
<key>pdf</key>
<string>001_item01</string>
</dict>
<key>Item 2</key>
<dict>
<key>index</key>
<integer>1</integer>
<key>thumb</key>
<string>002_item02.png</string>
<key>pdf</key>
<string>002_item02</string>
</dict>
等等……
我可以从下面的 plist 中构建字典,但我还没有弄清楚如何确定顺序。我需要根据项目编号或索引来按顺序拉取每个项目。
NSDictionary * myDict = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Items" ofType:@"plist"]];
其实我在迭代的时候,顺序貌似是随机的:
for(id key in myDict)
NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);
2013-04-27 18:12:52.576 dicTest[47865:c07] 007_item07.png
2013-04-27 18:12:52.577 dicTest[47865:c07] 052_item52.png
2013-04-27 18:12:52.577 dicTest[47865:c07] 045_item45.png
2013-04-27 18:12:52.577 dicTest[47865:c07] 038_item38.png
2013-04-27 18:12:52.578 dicTest[47865:c07] 010_item10.png
2013-04-27 18:12:52.578 dicTest[47865:c07] 008_item08.png
2013-04-27 18:12:52.578 dicTest[47865:c07] 046_item46.png
2013-04-27 18:12:52.579 dicTest[47865:c07] 009_item09.png
尝试根据索引按顺序抓取项目(字典):
NSDictionary * dictionary = [myDict objectForKey:[myDict.allKeys objectAtIndex:i]];
【问题讨论】:
标签: objective-c dictionary plist nsdictionary