我创建了标题,用户名和密码的三个文本字段。 我想要这样,如果标题尚未在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)
}
}
}
答案 0 :(得分:1)
将int
的创建移至holder
。
else