我有这个简单的代码将对象保存在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
对于任何帮助,在此先感谢。

最佳答案

找到了解决方案:

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)")
    }
}

关于swift - Coredata : error in constraints,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44564420/

10-12 18:47