swiftnscodingnskeyedarchiveruserdefaults

How to unarchive object using NSKeyedUnarchiver?


**I'm using this class: **

class Person: NSObject, NSCoding {
    var name: String
    var image: String
    
    init(name: String, image: String) {
        self.name = name
        self.image = image
    }
    
    required init(coder aDecoder: NSCoder){
        name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
        image = aDecoder.decodeObject(forKey: "image") as? String ?? ""
    }
    
    func encode(with coder: NSCoder) {
        coder.encode(name, forKey: "name")
        coder.encode(image, forKey: "image")
    }
}

For archiving, i used this method:

if let savedData =  try? NSKeyedArchiver.archivedData(withRootObject: people, requireSecureCoding: false)

whrere people is Person class array [Person]

As for unarchiving, this method:

NSKeyedUnarchiver.unarchivedTopLevelObjectWithData()

is deprecated... which method should i use now ?


Solution

  • You now must tell the system what type you expect rather than simply unarchiving whatever is found:

    try NSKeyedUnarchiver.unarchivedArrayOfObjects(ofClass: Person.self, from: savedData)