I have a simple CoreData data model with:
name
timestamp
ident
where ident is a unique constraint.
With the following example code I try to insert a duplicate on the one hand and to make a duplicate out of an existing object on the other hand. As expected, an exception is thrown.
struct CV:View {
@Environment(\.managedObjectContext) private var moc
@FetchRequest(sortDescriptors: [])
private var persons: FetchedResults<PersonCD>
var body: some View {
VStack{
Button("add Person A"){addPerson(id: "A")}
Button("set first Person A"){persons[0].ident = "A"}
Button("save Context"){saveContext()}
}
}
private func saveContext(){
do {
try moc.save()
} catch {
let nsError = error as NSError
print(type(of: error))
print("Unresolved error \(nsError), \(nsError.userInfo)")
print("d:\(nsError.domain)")
print("c: \(nsError.code)")
print("ue: \(nsError.underlyingErrors)")
print("cn \(nsError.className)")
print("ds \(nsError.description)")
}
}
private func addPerson(id:String) {
let newPerson = PersonCD(context: moc)
newPerson.timestamp = Date()
newPerson.ident=id
}
}
Two questions about this:
- What is the easiest way to distinguish the exception from other possible exceptions and react to it (I can only see an NSError)?
- Is it possible to get the information about which objects are in conflict, which is available in the description, as a reference to the duplicate objects?