【问题标题】:initWithContentsOfFile reads file in wrong orderinitWithContentsOfFile 以错误的顺序读取文件
【发布时间】:2011-12-08 23:39:23
【问题描述】:

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

【问题讨论】:

  • 在字典中,顺序无关紧要,只要键值对匹配,因为查找是基于键,而不是它们的顺序。
  • 那么,如果我有一个有序列表来循环,那么数组会更好吗?
  • 是的,数组将是这样做的首选方法。

标签: objective-c nsdictionary initwithcontentsoffile


【解决方案1】:

initWithContentsOfFile: 不一定有问题。

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 2012-01-24
    相关资源
    最近更新 更多