Issue with UserDefaults (converting data to array and back)

88 Views Asked by At

What I want to do:

I want to get an array from UserDefaults that I saved beforehand and append a custom object to it. Afterwards I want to encode it as a Data-type again and set this as the UserDefaults Key again.

My problem:

The encoding part is what is not working as intended for me. It says: -[__SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x60000011a540

But I do not know how to fix this.

Below is my code for more context:

do {

let decoded  = defaults.object(forKey: "ExArray") as! Data
var exo = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(decoded) as! [Exerc]
exo.append(datas[indexPath.row])

let enco = try NSKeyedArchiver.archivedData(withRootObject: exo, requiringSecureCoding: false)   <- Here is the error
defaults.set(enco, forKey: "ExArray")

} catch {

print("Error encoding custom object NOSEARCHO")

}

This is how Exerc looks:

struct Exerc: Codable {
    var title: String
    var exID: String
}
1

There are 1 best solutions below

1
Mojtaba Hosseini On BEST ANSWER

Seems like you are not using the archiver features, so why don't you just use the codable?

do {
    
    let key = "ExArray"
    let decoded = defaults.data(forKey: key)!
    var exo = try JSONDecoder().decode([Exerc].self, from: decoded)
    exo.append(datas[indexPath.row])

    let enco = try JSONEncoder().encode(exo)
    defaults.set(enco, forKey: key)

} catch {
    print("Error encoding/decoding custom object NOSEARCHO", error)
}

It just a simple refactored MVP of the original code, but you can even work a bit on this and make it human readable right in the plist file!