【发布时间】:2019-11-06 07:28:05
【问题描述】:
在我的场景中,我需要将 array 值存储到 UserDefault 并检索相同的数据。当用户再次打开特定的viewcontroller时,检索数据需要加载到同一个数组中。下面是我正在尝试的代码。我不知道如何以正确的方式将数组输出值下方的 store 和 retrieve 放入 UserDefaults 中。请帮我解决这个问题。
将数据存储到数组中
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: true)
let item = searching ? filteredData[indexPath.row] : membersData[indexPath.row]
if let cell = tableView.cellForRow(at: indexPath) {
if cell.accessoryType == .checkmark {
cell.accessoryType = .none
// UnCheckmark cell JSON data Remove from array
self.selectedRows = selectedRows.filter{$0 != indexPath.row}
self.selectedValues.remove(item) // Here Data Removing Into Array
} else {
cell.accessoryType = .checkmark
// Checkmark selected data Insert into array
self.selectedRows.append(indexPath.row) //select
self.selectedValues.insert(item) // Here Data Storing Into Array
}
}
}
将数组数据保存到 UserDefault
@IBAction func doneAction(_ sender: Any) {
// Selected Row Index Store
UserDefaults.standard.set(selectedRows, forKey: "SelectedIndexes")
// Here need to store Selected values
self.dismiss(animated: true, completion: nil)
}
将 UserDefault 存储的数据重新加载到同一个数组中 (viewDidLoad)
self.selectedRows = UserDefaults.standard.value(forKey: "SelectedIndexes") as? [Int] ?? []
// Here how to retrieve SelectionValue and Load into `selectedValues` array
可编码
// MARK: - ListData
struct ListData: Codable, Hashable {
let userid: String?
let firstname, designation: String?
let profileimage: String?
var isSelected = false
private enum CodingKeys : String, CodingKey {
case userid, firstname, designation, profileimage
}
}
数组数据
SELECT VALUE:[ListData(userid: Optional("1"), firstname: 可选(“abc”),名称:可选(“English”),个人资料: 可选(“url”)),ListData(用户ID: 可选(“2”),名字:可选(“def”),名称: 可选(“数字”),profileimage: 可选(“url”))] 选择行:[0, 1]
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
-
@PGDev 搜索后的搜索结果复选标记无法正常工作,但没有搜索复选标记工作正常。
标签: ios swift nsuserdefaults