首页 > 解决方案 > 存在 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)")
    }

}

标签: iosswiftcore-data

解决方案


您可以在每次插入之前获取所有记录并验证新的患者 ID在插入之前不存在,如果存在则显示警报

获取数组后

if fetchedArray.map{$0.patientID}.contains(newID) {
   // show alert here as id exists
   return
}
// proceed in saving the new record 

推荐阅读