如何在Swift 4的UserDefalts中设置自定义类数组数据

问题描述

我有一个数组列表

private var deviceArray:[SearchPeripheral]? = []

我想将设备数组的数据保存在UserDefaults中,但是在存储它时会崩溃。 请帮助我

谢谢。

解决方法

您不能在UserDefaults中存储自定义模型。您可以进行以下改进以将对象另存为 [[String:Any]]

struct SearchPeripheral: Codable {
    let name: String
    let model: String
}

extension SearchPeripheral {
    var dictionary: [String:Any] {
        let data = try! JSONEncoder().encode(self)
        let any = try! JSONSerialization.jsonObject(with: data)
        return any as! [String:Any]
    }

    init?(_ dict: [String:Any]) {
        guard let peripheral = (try? JSONSerialization.data(withJSONObject: dict)).flatMap({
            try? JSONDecoder().decode(SearchPeripheral.self,from: $0)
        }) else {
            return nil
        }
    
        self = peripheral
    }
}

保存SearchPeripheral数组:

func save(_ peripherals: [SearchPeripheral]) {
    let allPeripherals = peripherals.compactMap({$0.dictionary})
    UserDefaults.standard.set(allPeripherals,forKey: "peripherals")
}

获取SearchPeripherals数组:

func getPeripherals() -> [SearchPeripheral] {
    let allPeripherals = UserDefaults.standard.array(forKey: "peripherals") as? [[String:Any]] ?? []
    let peripherals = allPeripherals.compactMap(SearchPeripheral.init)
    return peripherals
}