ccd
ccd

Reputation: 6948

The error from NSKeyedUnarchiver.unarchiveObject to PropertyListDecoder().decode

I try to format the code from NSCoding to Codable, the old one using NSKeyedUnarchiver to unarchive.

// ItemStore.swift

var allItems = [Item]()
let itemArchiveURL: URL = {
    let documentsDirectories =
        FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentDirectory = documentsDirectories.first!
    return documentDirectory.appendingPathComponent("items.archive")
}()

init() {
    if let archivedItems =
        NSKeyedUnarchiver.unarchiveObject(withFile: itemArchiveURL.path) as? [Item] {
        allItems = archivedItems
    }
}

And now I adjust this function to the new one PropertyListDecoder().decode using Codable to unarchive.

init() {
    do {
        let itemsdata = try Data(contentsOf: itemArchiveURL)
        if let archivedItems = try PropertyListDecoder().decode(allItems.self, from: itemsdata) as? [Item] {
            allItems = archivedItems
        }
    }
    catch {
        print("Error archiving data: \(error)")
    }
}

I'm confuse the Xcode report Cannot invoke 'decode' with an argument list of type '([Item], from: Data)' error message, why the Data(contentsOf:) not return the Data value?

Upvotes: 0

Views: 107

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100541

Replace

if let archivedItems = try PropertyListDecoder().decode(allItems.self, from: itemsdata) as? [Item] {

With

allItems = try PropertyListDecoder().decode([Item].self, from: itemsdata) 

Upvotes: 1

Related Questions