TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Project 12 - Problem with unarchiving :(

Forums > Swift

@mina  

having the NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(savedPeople) deprecated from iOS 12 I'm trying to use NSKeyedUnarchiver.unarchivedObjects(ofClass: [Person].self, from: savedPeople) { people = decodedPeople } but its telling me that [people] must inherit from nsobject and conform to nscoding. How do I solve this?

3      

Hi @mina

This should work, but I haven't checked on real device so feedback would be appreciated.

Update your Person Class as follows:

class Person: NSObject, NSSecureCoding {

    static var supportsSecureCoding = true

    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 aCoder: NSCoder) {
        aCoder.encode(name, forKey: "name")
        aCoder.encode(image, forKey: "image")
    }
}

and then use as below:

    let defaults = UserDefaults.standard
    if let savedPeople = defaults.object(forKey: "people") as? Data {
        if let decodedPeople = try? NSKeyedUnarchiver.unarchivedArrayOfObjects(ofClass: Person.self, from: savedPeople) {
        people = decodedPeople
      }
    }

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.