ios - 当存在 NSConstraintConflict 时显示 UIAlertController

标签 ios swift core-data

我正在将数据插入到我的 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/

相关文章:

ios - 如何从父ViewController中的ContainerView获取值?

ios - 为什么多次调用 UITableView numberOfRowsInSection?

ios - setNeedsDisplay 不适用于 UIImageView 的子类

ios - 在 xCode 中解析嵌套的 NSDictionary 和 NSArray 数据

ios - 谓词的核心数据提取请求错误

iOS:将文本保存到文档目录或核心数据实体?

ios - iTunes Connect - 准确的元数据

ios - 你能帮忙解决 data.entry.init 问题吗?

SwiftyJson 不从 NSBundle 解析

json - 如何使用 Alamofire 恢复活力