ios - 存在 NSConstraintConflict 时显示 UIAlertController
问题描述
我正在将数据插入我的 CoreData 堆栈(它只有一个具有几个属性的实体)。在 Xcode 中,我将属性“ patientID ”设置为唯一约束。尝试添加新条目时,这会按预期进行,并在 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)")
}
}
解决方案
您可以在每次插入之前获取所有记录并验证新的患者 ID在插入之前不存在,如果存在则显示警报
获取数组后
if fetchedArray.map{$0.patientID}.contains(newID) {
// show alert here as id exists
return
}
// proceed in saving the new record
推荐阅读
- c# - 内存中的 SQLite 与 dapper 生成不存在的表错误
- c - strcpy 无法与动态分配的 char 数组一起正常工作
- scala - 线程“主”java.io.FileNotFoundException 中的 Scala 异常
- python - 在 sqlalchemy 数据库中插入和查询 numpy 数组的最合适方法是什么?
- python - wand.py gif 重新缩放的奇怪行为
- python - 在多个列上并行运行回归
- css - Css flex 垂直对齐
- ios - WebRTC iOS SignalEncoderTimedOut
- android - HttpURLConnection 帖子不起作用
- java - 为什么 Hibernate 为 *-to-many 表上的列引用创建序列?