ios - Save selected items in array of objects to UserDefaults in swift 4
问题描述
I have decoded my Json to structure and now I have array of objects that each objects has some values so I want when user select item in collection View the selected object in array append to the array of objects in UserDefaults I read similar questions so I used this Function Below But it won't work
@objc func likeOrDislike (_ sender : UIButton!) {
let arrays = UserDefaults.standard.value(forKey: "Liked") as? [ListsModel.ResultValue]
print(arrays as Any)
var items = arrays
let item = self.adv.resultValue[sender.tag]
if arrays != nil {
if items!.contains(where: {($0.id == item.id)}) {
items!.filter({($0.id == item.id)})
} else {
items!.append(item)
}
} else {
items = [item]
}
UserDefaults.standard.setValue(items, forKey: "Liked")
UserDefaults.standard.synchronize()
}
and here is the model that I use for decode
public class ListsModel {
struct Response : Decodable {
var resultValue : [ResultValue]
}
struct ResultValue : Decodable {
let id : String?
let title : String?
let user_id : String?
let username : String?
let user_image : String?
let release_date : String?
let start_date : String?
let salary : String?
let salary_id : String?
let work_field_id : String?
let adv_type_id : String?
let work_field : String?
let description : String?
let adv_base_id : String?
let is_spec : String?
let status : String?
let p_expire_date : String?
}
}
解决方案
通过 stringify 将所有模型对象转换为字符串,然后存储到用户默认值并在您想要使用的地方使用。
推荐阅读
- node.js - 如何对来自 Alpha Vantage API 的金融系列数据应用阈值和分页?
- javascript - 如果变量不存在则返回 false
- javascript - 在 ASP.Net Core 5 MVC 控制器中,当传递一个包含小数的 JSON 对象 FromBody 时,模型始终为空
- c++ - 预编译头文件clang重新定义错误
- machine-learning - RLlib PPO 连续动作在 total_loss = inf 之后似乎变成了 nan?
- python-3.x - 当我使用 for 循环和随机森林回归时,定义函数(函数)的输出不是预期的
- javascript - 为什么即使我不导入/需要顶部的模块,我的节点文件的依赖项也能工作?
- javascript - 如何在我制作的nodejs中导出一个函数
- python - 如何对连续元组进行分组并通过 Python 在列表中选择最大一个?
- julia - 如何在 Flux.jl 中使用损失函数