用户默认需要时间来保存在swift中

时间:2018-06-15 11:10:49

标签: ios swift nsuserdefaults

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

此代码是

     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的app时,Userefault将无法保存。 userDefault是否需要时间来保存

1 个答案:

答案 0 :(得分:4)

删除UserDefaults.standard.synchronize()

它会让您的应用等待。根据{{​​3}}:"这种方法是不必要的,不应该使用。"