简体   繁体   中英

How to save class in swift to userdefaults without arguments

I was unable to find a suitable community to post in, so I am sorry if this is off-topic. I am having trouble saving a custom class in swift to userdefaults. Every other answer I have seen requires initializing the class with arguments but I am looking for a way around that when encoding. I also wonder if userdefaults is the best choice? It is a large amount of data but I am trying to avoid using a relational database because I am just trying to save this data structure directly without creating a schema. It produces an error when adding mediations to the mediation object array and then trying to encode the data.

My code:

import Foundation

class SavedData: NSObject, NSCoding {
func encode(with aCoder: NSCoder) {
    aCoder.encode(mediations, forKey: "mediations")
    aCoder.encode(name, forKey: "name")
}

required convenience init?(coder aDecoder: NSCoder) {
    let name = aDecoder.decodeObject(forKey: "name") as! String
    let mediations = aDecoder.decodeObject(forKey: "mediations") as! [Mediation]
    self.init(name: name, mediations: mediations)
}


init(name: String, mediations: [Mediation]) {
    // Get Saved Mediations from memory
    self.mediations = mediations
    self.name = name
}

public var mediations: [Mediation]
var name: String = "foo"

class Mediation {

    init(name: String, role: String, data: [[String]]) {
        self.name = name
        self.data = Data(defendant: data[0], plaintiff: data[1])
    }

    var role: String = ""
    var name: String = ""
    var data: Data

    class Data {

        init(defendant: [String], plaintiff: [String]) {
            self.defendant = defendant
            self.plaintiff = plaintiff
        }
        var plaintiff: [String] = []
        var defendant: [String] = []
    }
}

func new_mediation (name: String, role: String, data: [[String]]) {
    let mediation = Mediation(name: name, role: role, data: data)
    self.mediations.append(mediation)
}

}

My favourite way to save array of custom class to UserDefaults is to use JSONEncoder.

So make sure your Mediation is Codable by:

Class Mediation: Codable

Then to save the array:

let encodedMediations = try! JSONEncoder().encode(mediations)
UserDefaults.standard.set(encodedMediations, forKey: "SavedMediations")

Finally to fetch the array:

if let savedMediations = UserDefaults.standard.data(forKey: "SavedMediations") {
   let decodedMediations = try! JSONDecoder().decode([Mediation].self, from: savedMediations)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM