NSDictionary init (contentsOfFile :) is deprecated, so now?

Recently (since iOS 11) init(contentsOfFile:)

to NSDictionary

become obsolete.

enter image description here

I wanted to be a prospective citizen, so I was looking for another way to load a property list (plist) into a type NSDictionary

. The only thing I could find is this PropertyListSerialization

, but it's comparatively cumbersome.

Here's what I came up with to show the difference:

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
}

      

I noticed that this answer here has been playing golf using PropertyListSerialization

up to less code than I came up with, but it's not obvious when reading Apple's 7 Years Feature List Programming Guide . And this example has 3 more depressions.

Am I missing a replacement convenience initializer somewhere else? Is this what we are doing now to load the plist into the dictionary?

+3


source to share


1 answer


This is not a fair comparison.

Actually literal translation

let myD = NSDictionary(contentsOfFile: path) as! [String : Any]

      

there is



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

      

In both cases, the code crashes if something goes wrong.

However, in both cases, you must do the correct error handling.

+2


source







All Articles