arrays - Swift4.2 如何将“struct”构造的二维数组保存到UserDefautls?
问题描述
通过使用下面的代码,我可以成功地将包含“struct”(即 [structData])的数组保存到 userDefautls。
// save [dataCell] encoded to JSON
func save(_ cellDatas: [cellData]){
let encoDatas = cellDatas.map{ try? JSONEncoder().encode($0)}
UserDefaults.standard.set(encoDatas, forKey: "datas")
}
// decode JSON array to [cellData]
func load() -> [cellData]{
guard let encodedData = UserDefaults.standard.array(forKey: "datas") as? [Data] else {
return []
}
return encodedData.map{try! JSONDecoder().decode(cellData.self, from: $0)}
}
// retrieve datas from UD
func retrieveData() -> [cellData]{
datas = UserDefaults.standard.array(forKey: "datas") == nil ? initialData : load()
return datas
}
但是,现在我需要保存一个二维数组,即 [[structData]] 以便我尝试了这些代码,替换了一些。但它没有用。
// save [dataCell] encoded to JSON
func saveTableList(_ tableList: [[cellData]]){
let encoDatas = tableList.map{ try? JSONEncoder().encode($0)}
UserDefaults.standard.set(encoDatas, forKey: "tableList")
}
// decode JSON array to [cellData]
func loadTableList() -> [[cellData]]{
guard let encodedData = UserDefaults.standard.array(forKey: "tableList") as? [[Data]] else {
return []
}
return encodedData.map{try! JSONDecoder().decode(cellData.self, from: $0)}
// this $0 has the error that "Cannot convert value of type '[Data]' to expected argument type 'Data'"
//so I tryied this way instead.
// return encodedData.map{try! JSONDecoder().decode(cellData.self, from: encodedData)}
//but it didn't work properly
}
// retrieve datas from UD
func retrieveTableListData() -> [cellData]{
datas = UserDefaults.standard.array(forKey: "datas") == nil ? initialData : load()
return datas
}
如何将 [[struct]] 的二维数组编码/解码为 JSON 并使用 userDefautls 保存/加载它?
解决方案
为什么不一次编码整个二维数组而不是创建编码对象数组。我试过了,它奏效了。
func saveTableList(_ tableList: [[cellData]]) {
guard let encodedCellData = try? JSONEncoder().encode(tableList) else {
print("Error")
return
}
UserDefaults.standard.set(encodedCellData, forKey: "tableList")
}
func loadTableList() -> [[cellData]] {
guard let encodedCellData = UserDefaults.standard.value(forKey: "tableList") as? Data,
let cellData = try? JSONDecoder().decode([[cellData]].self, from: encodedCellData) else {
return []
}
return cellData
}
推荐阅读
- node.js - 最佳实践:使用 create-react-app 的客户端和服务器的文件夹结构
- java - jpa @SequenceGenerator.allocationSize 是什么意思?
- android - 我可以使用 admob 奖励广告来删除横幅广告吗?
- c++ - 在多个线程上发布任务时 boost::asio::thread_pool 线程安全吗?
- c# - List.Add 与 List.Insert
- javascript - 如何将新对象添加到 Observer 类型 - javascprit
- django - 使用覆盖的 ,save() 方法模型创建数据迁移
- reporting-services - SSRS 报告根据正在加载报告的浏览器显示隐藏消息
- c++ - 背包问题根据每单位重量的利润对数组进行排序
- hbase - 列过滤器(例如列名 = X)与 HBase 中的行过滤器性能?