Coredata:约束错误

问题描述 投票:0回答:1

我有这个简单的代码来将对象保存在 coredata 中。 在我的 xcatamodel 中,我将约束设置为“firstName”: Picture。 删除“学生”实体中的所有条目后,代码可以正常工作。 但只有一次。 当我第二次保存同一组时,我收到“致命错误”。

func saveStudent() {

    let student: Student = NSEntityDescription.insertNewObject(forEntityName: "Student", into: DatabaseController.getContext()) as! Student

                student.firstName = "henry"
                student.lastName = "miller"
                student.age = 22

    DatabaseController.saveContext()
    let fetchRequest: NSFetchRequest<Student> = Student.fetchRequest()

    do {
        let searchResults = try DatabaseController.getContext().fetch(fetchRequest)
        print("number of results: \(searchResults.count)")
        for result in searchResults as [Student] {
            print("\(result.firstName) \(result.lastName) \(result.age)")
        }
    } catch {

        print ("error: \(error)")
    }
}

据我所知,该约束是为了识别潜在的重复项。 有人知道如何解决这个问题吗? 错误如下:Picture 如需任何帮助,请提前致谢。

swift core-data error-handling constraints
1个回答
0
投票

找到解决方案:

func saveStudent() {

    let student: Student = NSEntityDescription.insertNewObject(forEntityName: "Student", into: DatabaseController.getContext()) as! Student

                student.firstName = "henry"
                student.lastName = "miller"
                student.age = 22

    DatabaseController.getContext().mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

    DatabaseController.saveContext()
    let fetchRequest: NSFetchRequest<Student> = Student.fetchRequest()

    do {
        let searchResults = try DatabaseController.getContext().fetch(fetchRequest)
        print("number of results: \(searchResults.count)")
        for result in searchResults as [Student] {
            print("\(result.firstName) \(result.lastName) \(result.age)")
        }
    } catch {

        print ("error: \(error)")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.