我正在使用下面的代码阅读plist文件。 我的问题是该文件似乎是以一些随机顺序读取的。 顺序始终相同(d,b,e,c,a,f)。 是否可以按照文件中输入的“正确”顺序读取文件?
prefs.plist文件内容:
<dict>
<key>a</key>
<string>1</string>
<key>b</key>
<string>2</string>
<key>c</key>
<string>3</string>
<key>d</key>
<string>4</string>
<key>e</key>
<string>5</string>
<key>f</key>
<string>6</string>
</dict>
代码:
//Get file name
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"prefs" ofType:@"plist"];
//Load preferences into dictionary
NSMutableDictionary *myDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
myDict的打印输出:
<CFBasicHash 0x4e1f330 [0xe39400]>{type = mutable dict, count = 6,
entries =>
0 : <CFString 0x4e1f120 [0xe39400]>{contents = "d"} = <CFString 0x4e1f180 [0xe39400]>{contents = "4"}
1 : <CFString 0x4e1f160 [0xe39400]>{contents = "b"} = <CFString 0x4e1f320 [0xe39400]>{contents = "2"}
3 : <CFString 0x4e1f130 [0xe39400]>{contents = "e"} = <CFString 0x4e1f190 [0xe39400]>{contents = "5"}
4 : <CFString 0x4e1f110 [0xe39400]>{contents = "c"} = <CFString 0x4e1f170 [0xe39400]>{contents = "3"}
5 : <CFString 0x4e1f140 [0xe39400]>{contents = "a"} = <CFString 0x4e1f1a0 [0xe39400]>{contents = "1"}
6 : <CFString 0x4e1f150 [0xe39400]>{contents = "f"} = <CFString 0x4e1f310 [0xe39400]>{contents = "6"}
}
答案 0 :(得分:2)
这不一定是initWithContentsOfFile:
的问题。
如果这是你的意图和你的字典,只需创建一个有序数组,如下所示:
NSArray * keys = [myDict keys];
NSArray * orderedKeys =
[keys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
当然,您可以使用比较或定义自己的比较。
然后你可以通过有序键来枚举像数组一样。