UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Project 12 - Problem with unarchiving :(

Forums > Swift


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?


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


Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free 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.