I have this simple code to save an object in coredata. In my xcatamodel I set a constraint to "firstName": Picture. After deleting all entries in the "Student" Entity, the code works fine. But only for one time. When i´m saving the same set a second time, i´m getting "fatal 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.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)")
}
}
As far as I´m understanding, the constraint is meant to recognize a potential dublicate. Anyone an idea how to solve this problem? Here´s the error: Picture For any help, thanks in advance.
答案 0 :(得分: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)")
}
}