来自模型时如何以用户默认值保存数据

时间:2019-11-24 21:26:37

标签: ios swift userdefaults

我有一个这样的模型

struct House: Codable {
    let address: String?
    let rooms: String?
    let garage: Garage
}

struct Garage: Codable {
    let space: String?
    let numbers_of_ cars: String?
}

我从api获取数据并设置为可以显示它, 现在我需要保存在userdefaults中,以便在没有wifi网络的情况下显示信息

我正在尝试这样

var itemItems = [House]()

fileprivate func fetchData() {
        Service.shared.fetchCourses { (houses, err) in
            if let err = err {
                print("Failed to fetch houses:", err)
                return
            }

        self.itemItems = houses!

        var itemsToSave = [House]()
        for i in 0..<self.itemItems.count {
            itemsToSave.append(self.itemItems[i])
        }

        UserDefaults.standard.set(arrayToSave, forKey : "arrayToSave")

        }
    }

但是!!我得到一个错误 检查图像

https://i.ibb.co/bHhtj28/Captura-de-Pantalla-2019-11-24-a-la-s-4-25-18-p-m.png

1 个答案:

答案 0 :(得分:1)

您无法将自定义结构直接保存到UserDefaults

但是由于两个结构都符合Codable编码

var itemItems = [House]()

fileprivate func fetchData() {
    Service.shared.fetchCourses { (houses, err) in
        if let err = err {
            print("Failed to fetch houses:", err)
            return
        }

        self.itemItems = houses!
        do {
           let data = try JSONEncoder().encode(self.itemItems)
           UserDefaults.standard.set(data, forKey : "houses")
        } catch { print(error) }      
    }
}