gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:32:44 25 4
gpt4 key购买 nike

我想保存字典,但我不断收到此错误消息:“SwiftValueencodeWithCoder:]:无法识别的选择器发送到实例”。这就是我尝试保存字典的方法:

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)
    }
    }

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

享受吧!

关于arrays - 字典保存错误 "SwiftValue encodeWithCoder:]: unrecognized selector sent to instance",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58788530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com