字典保存错误 "SwiftValue encodeWithCoder:]: unrecognized selector sent to instance"

Dictionary save error "SwiftValue encodeWithCoder:]: unrecognized selector sent to instance"

我想保存字典,但我不断收到此错误消息:"SwiftValue encodeWithCoder:]: unrecognized selector sent to instance"。这就是我尝试保存字典的方式:

func savePlaces(){
     let placesData = NSKeyedArchiver.archivedData(withRootObject: Resultaat?.reisdelen)
     UserDefaults.standard.set(placesData, forKey: "Reis")
}

我如何尝试加载词典:

var Reis = [reisdelen]()
func loadPlaces(){
     let placesData = UserDefaults.standard.object(forKey: "Reis") as? NSData

     if let placesData = placesData {
         let placesArray = NSKeyedUnarchiver.unarchiveObject(with: placesData as Data) as? [reisdelen]

         if let placesArray = placesArray {
             Reis = placesArray
             TableView.reloadData()
         }
     }
 }

我的结构:

struct reismogelijkheden: Decodable {
    let reisdelen: [reisdelen]?
    let reistijd: reistijd?
    let reistijdActueel : reistijdActueel?
    let aantalOverstappen: Int?
    let vertrektijd: String?
    let vertrektijdVertraging: vertrektijdVertraging?
    let aankomsttijd: String?
}

struct reisdelen: Decodable {
    let vervoerder: String?
    let richting: String?
    let treinnummer: String?
    let lijn: String?
    let stops: [stops]?
    let modaliteit: modaliteit?
    let travelTimeInMinutes: Int?
    let travelDistanceInMeters: Int?
}

您可以像这样将模型保存到 UserDefaults

  • 首先你应该创建一个模型的实例

  • 然后您可以将模型保存到 UserDefaults,例如:

    let encoder = JSONEncoder()
    if let encoded = try? encoder.encode(modelInstance) {
        let defaults = UserDefaults.standard
        defaults.set(encoded, forKey: "Reis")
    }
    

    您可以像这样从 UserDefaults 获取模型

    if let savedItem = defaults.object(forKey: "Reis") as? Data {
        let decoder = JSONDecoder()
        if let loadedItem = try? decoder.decode(YourModel.self, from: savedItem) {
            print(loadedItem)
        }
    }
    

我希望这是你试图找到的答案。

尽情享受吧!