我正在将数据插入到我的 CoreData 堆栈中(该堆栈只有一个带有一些属性的实体)。在 Xcode 中,我将属性“patentID”设置为唯一约束。
当尝试添加新条目时,这会按预期执行,并在 Xcode 控制台中引发错误 (NSConstraintConflict
)。但是,应用程序内没有显示任何内容。
我如何添加 UIAlertController 来声明这是重复条目?
我当前保存到CoreData的函数如下:
func save(newID: String, newDOB: String, newAge: String, newGender: String, newHeight: String, newWeight: String, newRace: String, newADLS: String) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
// 1
let managedContext = appDelegate.persistentContainer.viewContext
// 2
let entity = NSEntityDescription.entity(forEntityName: "Patient", in: managedContext)!
let person = NSManagedObject(entity: entity, insertInto: managedContext)
// 3
person.setValue(newID, forKeyPath: "patientID")
person.setValue(newDOB, forKey: "dob")
person.setValue(newAge, forKey: "age")
person.setValue(newGender, forKey: "gender")
person.setValue(newHeight, forKey: "height")
person.setValue(newWeight, forKey: "weight")
person.setValue(newRace, forKey: "race")
person.setValue(newADLS, forKey: "adls")
// 4
do {
try managedContext.save()
dismiss(animated: true, completion: nil)
//No need for this - this occurs appends during viewWillAppear
//ids.append(person)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
最佳答案
您可以在每次插入之前获取所有记录,并验证新的patentID在插入之前不存在,如果存在则显示警报
获取数组后
if fetchedArray.map{$0.patientID}.contains(newID) {
// show alert here as id exists
return
}
// proceed in saving the new record
关于ios - 当存在 NSConstraintConflict 时显示 UIAlertController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52238537/