如果不满足某些条件,如何防止保存输入

时间:2019-05-05 20:08:09

标签: ios swift

我创建了标题,用户名和密码的三个文本字段。 我想要这样,如果标题尚未在coredata中存在,则将其添加,但是如果标题已经存在,则显示和警告消息(有效),但由于某种原因仍会添加到coredata中。 / p>

这是我的代码:

  @IBAction func savePasswordButton(_ sender: Any) {

        if let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext {

            let holder = PasswordCoreData(entity: PasswordCoreData.entity(), insertInto: context)

            if let title = createHolderItem.text {
                holder.item = title
                holder.username = createHolderUsername.text!
                holder.password = createHolderPassword.text!
            }

            if homeVC.mainframe.contains(where: { $0.username == holder.username }) {
                let title = "Duplicate"
                let message = "(holder.item) already exists"
                let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)

                alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: { (action) in alert.dismiss(animated: true, completion: nil)

                }))
                self.present(alert, animated: true, completion: nil)
            }
            else {
                try? context.save()

                navigationController?.popViewController(animated: true)
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

int的创建移至holder

else
相关问题