ios – NSDictionary init(contentsOfFile :)现已弃用,现在怎么办?

ios – NSDictionary init(contentsOfFile :)现已弃用,现在怎么办?,第1张

概述最近(从iOS 11开始),NSDictionary中的init(contentsOfFile :)被弃用了. 我想成为一个具有前瞻性思维的公民,所以我寻找另一种方法将属性列表(plist)加载到NSDictionary类型中.我唯一能找到的是PropertyListSerialization,但比较麻烦. 这就是我想出的差异: func dealWithFakeConf(atPath path: 最近(从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加载到Dictionary中吗?

解决方法 这不是一个公平的比较.

实际上是字面翻译

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]

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

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

总结

以上是内存溢出为你收集整理的ios – NSDictionary init(contentsOfFile :)现已弃用,现在怎么办?全部内容,希望文章能够帮你解决ios – NSDictionary init(contentsOfFile :)现已弃用,现在怎么办?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1067790.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-26
下一篇2022-05-26

发表评论

登录后才能评论

评论列表(0条)

    保存