I know that you can observe changes to entities you've fetched with @ObservedObject.
The problem is best illustrated with an example: If I had an entity school with a one to many relationship to students and each student has a property numberOfPencils then I want to recalculate the sum of all pencils within a school whenever a student in the school changes his numberOfPencils property.
If I access all the students through the schools entity (which is an @ObservedObject) then I only get updates to the sum if a new student is added but not when an existing student changes his numberOfPencils because student objects can only be observed one by one as far as I know.
The only thing I could come up with is setting up a NSFetchedResultsControllerDelegate with a fetchRequestPredicate that gets all the students associated with a school through some keyPath from student to school which uniquely identifies the school. But that seems like a hacky way to do it and there surely must be a better solution that is eluding me.
Basically I want to get notified of changes to any of the students associated with a school.
CodePudding user response:
Derived properties is definely a good way to go.
But to clarify: @ObservedObject can also get updated on change of the item. You just have to manually trigger the update with objectWillChange.send()
Say your School
cell looks like this:
struct SchoolCell: View {
@ObservedObject var school: School
var body: some View {
HStack {
let pencils = school.pupilsArray.reduce(0, {$0 $1.numberOfPencils})
Text(school.name)
Spacer()
Text(verbatim: "\(pencils) pencils")
.foregroundColor(.secondary)
}
}
}
then the Pupil
modify would work like this:
// ...
@ObservedObject var school: School
// ...
Button(" 10 Pencils") {
school.objectWillChange.send()
pupil.numberOfPencils = 10
try? viewContext.save()
}
It is important though that SchoolCell
IS an own struct, so it gets refreshed when its @ObservedObject school changes.