Hello everyone, I am beginner in SwiftUI and Core Data, I'm facing the following problem and I'm not sure how to proceed.
My app can have many departments, each department can have many projects, each project can have many people.
Projects and people can have tasks, so I have a view with the details of a person, and two lists: the tasks assigned to the person and the unassigned tasks of his project. I can move a task from a person to his project and vice versa with a button.
@StateObject var person: Person
var department: Department
...
var body: some View {
...
ForEach(taskPerson) { task in
Text("\(task.name ?? "")")
// move task from person to project
Button(action: {
task.person = nil
// there's a try-catch here
try viewContext.save()
})...
}
...
Text("\(project.name!)")
...
let unassignedProjectTasks = tasks.filter { $0.project != nil && $0.person == nil && $0.project?.name == person.project?.name }
ForEach(unassignedProjectTasks) { task in
...
// move task from project to person
Button(action: {
task.person = person
// there's a try-catch here
try viewContext.save()
})...
}
}
I'm using @StateObject because I have a button to edit the project assigned to a person, and I need the projects of the department:
Button("Change person project") {
sheetToChangeProject.toggle()
}
.sheet(isPresented: $sheetToChangeProject) {
ProjectPersonEditView(department: department)
.environment(\.managedObjectContext, self.viewContext)
.environmentObject(person)
}
When that happens the person's details are correctly refreshed.
It all works great except for the last element of the list when I move from person to project or vice versa.
There's a try catch in both viewContext.save() but the execution doesn't stop there, it goes directly to an odd file with:
SwiftUI`generic specialization <UniformTypeIdentifiers.UTType> of Swift.Array._checkSubscript(_: Swift.Int, wasNativeTypeChecked: Swift.Bool) -> Swift._DependenceToken:
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
Any ideas?
Thank you.