【问题标题】:NSDictionary init(contentsOfFile:) is deprecated so now what?NSDictionary init(contentsOfFile:) 已被弃用,现在怎么办?
【发布时间】: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


【解决方案1】:

这不是一个公平的比较。

其实是

的字面翻译
let myD = NSDictionary(contentsOfFile: path) as! [String : Any]

let rawData = try! Data(contentsOf: URL(fileURLWithPath: path))
let realData = try! PropertyListSerialization.propertyList(from: rawData, format: nil) as! [String:Any]

在这两种情况下,如果出现问题,代码都会崩溃。

但是,在这两种情况下,您都应该进行适当的错误处理。

【讨论】:

  • 感谢您下载代码。我很感激。我可以跳过 FileManager 步骤。但是,如果我在两种情况下都做同样的事情(不处理错误条件),那么 一个公平的比较,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-19
  • 2016-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多