首页 > 解决方案 > 用户默认值需要时间快速保存

问题描述

我有带有复选框的表格视图,我想保存选中的复选框。用于在用户下次打开应用程序时显示带有复选标记的选中复选框

因为这段代码是

     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 是否需要时间来保存

标签: iosswiftnsuserdefaults

解决方案


消除UserDefaults.standard.synchronize()

它会导致您的应用程序等待。根据文档:“这种方法是不必要的,不应该使用。”


推荐阅读