我有这个简单的代码来将对象保存在 coredata 中。 在我的 xcatamodel 中,我将约束设置为“firstName”: 。 删除“学生”实体中的所有条目后,代码可以正常工作。 但只有一次。 当我第二次保存同一组时,我收到“致命错误”。
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)")
}
}
找到解决方案:
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)")
}
}