gpt4 book ai didi

ios - 使用 UserDefault 快速存储和检索数组数据

转载 作者:行者123 更新时间:2023-11-29 05:20:26 25 4
gpt4 key购买 nike

在我的场景中,我需要将 array 值存储到 UserDefault 中并检索相同的数据。当用户再次打开该特定的 View Controller 时,检索数据需要加载到同一个数组中。下面是我正在尝试的代码。我不知道如何以正确的方式存储检索下面的数组输出值到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: Optional(“abc”), designation: Optional(“English”), profileimage: Optional("url")), ListData(userid: Optional(“2”), firstname: Optional(“def”), designation: Optional("Digital"), profileimage: Optional("url"))] SELECT ROW:[0, 1]

最佳答案

如果您想存储在 UserDefault 中,尽管不建议这样做。

var selectedValues: [Any] = [["id": 1, "name": "Adam"]]
selectedValues.append(["id": 2, "name": "Eve"])
UserDefaults.standard.set(selectedValues, forKey: "SelectedValues")
let result = UserDefaults.standard.array(forKey: "SelectedValues") ?? []

print(result)


Output : [{
id = 1;
name = Adam;
}, {
id = 2;
name = Eve;
}]

关于ios - 使用 UserDefault 快速存储和检索数组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58725069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com