0

我正在使用下面的代码读取 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"}
}
4

1 回答 1

2

这不一定是initWithContentsOfFile:.

如果这是您的意图和字典,只需创建一个有序数组,如下所示:

NSArray * keys = [myDict keys]; 
NSArray * orderedKeys =
 [keys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

当然,您可以使用比较或定义自己的来订购它们。

然后您可以像数组一样枚举有序键。

于 2011-12-08T15:39:23.200 回答