ios - 用户默认值需要时间快速保存
问题描述
我有带有复选框的表格视图,我想保存选中的复选框。用于在用户下次打开应用程序时显示带有复选标记的选中复选框
因为这段代码是
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let c = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! tabCell
c.lblC.text = arry?[indexPath.row]
/* for example
arry = ["1","2","3","4","5","6","7","8","9","10"]
seleted = ["1","2"]
*/
//print("indexpath--",indexPath.row)
if selected != nil
{
if (selected?.contains((arry?[indexPath.row])!))!
{
c.btnCheck.setBackgroundImage(#imageLiteral(resourceName: "check.png"), for: .normal)
}
else
{
c.btnCheck.setBackgroundImage(#imageLiteral(resourceName: "uncheck.png"), for: .normal)
}
}
c.btnCheck.tag = indexPath.row
c.btnCheck.addTarget(self, action:#selector(btnCheckClick(btn:)) , for: .touchUpInside)
return c
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete
{
if selected != nil
{
print(selected ?? "default")
selected = selected?.filter{$0 != arry![indexPath.row]}
print(selected ?? "default")
}
saveInUserDefault(value: selected ?? "default", key: "selectedChecks")
arry?.remove(at: indexPath.row)
tableView.reloadData()
}
}
@objc func btnCheckClick(btn:UIButton)
{
let img = btn.backgroundImage(for:.normal)
if img == #imageLiteral(resourceName: "check.png")
{
btn.setBackgroundImage(#imageLiteral(resourceName: "uncheck.png"), for: .normal)
if let indx = selected?.index(of: arry![btn.tag])
{
selected?.remove(at: indx)
saveInUserDefault(value: selected ?? "default", key: "selectedChecks")
print("after remove",selected ?? "default")
}
}
else
{
btn.setBackgroundImage(#imageLiteral(resourceName: "check.png"), for: .normal)
selected?.append(arry![btn.tag])
saveInUserDefault(value: selected ?? "default", key: "selectedChecks")
print("after append",selected ?? "default")
}
}
func saveInUserDefault(value:Any, key:String)
{
print("save",value)
UserDefaults.standard.set(value, forKey: key)
UserDefaults.standard.synchronize()
}
func getValueFromUserDefault(key:String) -> Any!
{
var v:[Any]! = []
if let a = UserDefaults.standard.value(forKey: key)
{
v = a as! [Any]
}
return v
}
有时,当我单击复选框并立即从 xcode 停止应用程序时,用户错误将无法保存。userDefault 是否需要时间来保存
解决方案
消除UserDefaults.standard.synchronize()
它会导致您的应用程序等待。根据文档:“这种方法是不必要的,不应该使用。”
推荐阅读
- android - 在通知生成器android中将颜色设置为图标
- c# - 在没有忙等待的情况下,我如何等待直到收到回调/通知?
- realm - 在 Yarn 安装中,Realm js 经常出错
- python - pytorch:LSTM 输入和输出维度和训练循环
- reactjs - 可以使用 Axios 模拟来自外部库的 API 调用吗?
- c - 为什么我可以释放结构的一部分它释放所有结构
- c - 我写的 Bcrypt 实现返回正确的成本和盐,但加密的消息不正确
- azure - Dynamics 365 和 Azure 事件中心集成
- python - Python:如何通过被另一个字符串列表分割的子字符串创建一个列表?
- sql - 展平/统一表行,其中条件与 ABAP 或 SQL 匹配数组