我正在使用contentsOfFile方法构建一个字典,并将该方法指向一个plist。我的代码如下:
func buildGraphicsDictionary() {
var theme: String = "defaultTheme"
var myDict: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource(theme, ofType: "plist") {
println("path: \(path)")
myDict = NSDictionary(contentsOfFile: path)
println("dict count: \(myDict?.count)")
} else {
println("could not find plist file")
}
}
找到了plist。我知道这是肯定的,因为我能够打印出路径,因为当我将plist字符串的名称更改为不存在的字符串时,我得到一个错误。所以我相信问题不在于访问plist。
但是,当我尝试使用count打印字典中的元素数时,控制台会报告myDict的值为nil。所以这告诉我问题实际上是我构建字典的方法(contentsOfFile)。令人困惑的是,我看过其他SO文章,其中使用相同的代码(表面上)成功。
有什么想法可以在这里发生什么?
答案 0 :(得分:1)
我已经测试了你的代码,它运行得很好。
也许是plist中的问题?
我用这个plist测试了你的代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>test1</key>
<string>one</string>
<key>test2</key>
<string>two</string>
</dict>
</plist>
在我的控制台中,我看到了:
dict count: Optional(2)
plist必须位于此处