swift Coredata:约束错误

rbpvctlc  于 11个月前  发布在  Swift
关注(0)|答案(1)|浏览(153)

我有这个简单的代码来保存coredata中的对象。在我的xcatamodel中,我设置了一个约束“firstName”:Picture。删除“Student”实体中的所有条目后,代码工作正常。但只有一次。当我第二次保存相同的集合时,我得到了“致命错误”。

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如需帮助,请提前感谢。

a5g8bdjr

a5g8bdjr1#

找到了解决方案:

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

字符串

相关问题