Core Data relationship counts not updating in view

Hello -

I have this Core data structure Project -> (one to many) TodoList -> (one to many) Todo

I have a view that is used to render a row in a List that is as follows.

struct TodoListRowView: View {

    @ObservedObject var todoList: TodoList

    var body: some View {
        HStack {
            Image(systemName: todoList.iconName ?? "list.bullet.clipboard")
            Text(todoList.name ?? "")
            Spacer()
            Text(String(todoList.todos?.filtered(using: NSPredicate(format: "completedAt == nil")).count ?? 0))
        }

    }

}

This view is wrapped in a NavigationLink in its parent view and when I drill into the TodoList it renders a view list of all the Todos in the selected TodoList. I have a checkbox toggle where I can set the Todo to completed which updates the completedAt attribute to a timestamp or nil if it's unchecked.

The problem I'm having is that changing the state of a Todo in one of these lists never updates the count. I'm not sure how to design this view such that when updating the todoList.todos entries it updates this count.

Thanks for any help!

Try to keep all DB operations at the TodoList level where you have a timer that triggers a reload which in turn updates TodoList count property which will update the view.

hi pocket,

whenever you make a change to a ToDo that could affect how a ToDoList is displayed in some view (in your case, the number of uncompleted todo items?), simply add the line

toDo.toDoList?.objectWillChange.send() // .toDoList is the relationship to the associated toDoList

that should trigger an update in any view that holds the associated ToDoList as an @ObservedObject.

hope that helps,

DMG

Core Data relationship counts not updating in view
 
 
Q