【发布时间】:2017-07-12 16:40:44
【问题描述】:
最近(从 iOS 11 开始),NSDictionary 中的 init(contentsOfFile:) 已弃用。
我想成为一个有远见的公民,所以我寻找另一种将属性列表 (plist) 加载到 NSDictionary 类型的方法。我唯一能找到的是PropertyListSerialization,但比较麻烦。
这是我想出的不同之处:
func dealWithFakeConf(atPath path:String) {
// So easy!
let myD:Dictionary<String,Any> = NSDictionary.init(contentsOfFile: path) as! Dictionary<String, Any>
let l = myD["location"] as? String ?? "BAD_STRING"
let q = myD["quantity"] as! Int
print("location = \(l)")
print("quantity = \(q.description)")
// Old is new again?!
guard let rawData = FileManager.default.contents(atPath: path) else {
fatalError("Sumpin done gone wrong!")
}
var format = PropertyListSerialization.PropertyListFormat.xml
let data = try? PropertyListSerialization.propertyList(from:rawData, options:[.mutableContainers], format:&format)
guard let realData = data as? Dictionary<String,Any> else {
fatalError("OMG! Now what?")
}
locationLabel.text = realData["location"] as? String ?? "BAD_STRING"
let qty:Int? = realData["quantity"] as? Int
quantityLabel.text = qty?.description
}
我注意到this answer over here 已将PropertyListSerialization 的使用减少到比我想出的更少的代码,但在阅读Apple's 7 year old docs Property List Programming Guide 时这并不明显。这个例子仍然深了 3 个缩进。
我是否在其他地方缺少替换的便利初始化程序?这就是我们现在将 plist 加载到字典中的方法吗?
【问题讨论】:
-
自 iOS 11 起已弃用,而不是 iOS 10。
-
谢谢@rmaddy,我已经修复了标签和文本以反映您的自信评论。
标签: ios nsdictionary plist ios11