Ch. 16, NSKeyedArchiver.archiveRootObject deprecated


Hi there,

the documentation is not helpful here :frowning:
what can I use to archive data instead of archiveRootObject?

Any help appreciated.

Edit: Okay, I could solve it myself:
I used the new ‘Codable’-Protocol instead of NSCoding. With Codable the initialization is automagic, you only have to declare the class or struct to conform to Codable:

class Item: NSObject, Codable {…

No need to implement encode and required init!

In itemStore.swift:

    func saveChanges() -> Bool {
        print("Saving items to \(itemArchiveURL.path)")
        do {
            let data = try PropertyListEncoder().encode(allItems)
            try data.write(to: itemArchiveURL)
            return true
        } catch {
            print("Error saving items: \(error) ")
        return false

The data is now written to the filesystem, but I do not manage to read it again. Any help appreciated.

I helped myself :slight_smile:

init() {
    typealias allItemsType = [Item]?
    do {
        let data = try Data(contentsOf: itemArchiveURL)
        let decoder = PropertyListDecoder()
        if let allItems = try decoder.decode(allItemsType.self, from: data){
            self.allItems = allItems
    } catch {
        print("itemStore init error: \(error)")