BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

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) { = 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


Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.