SwfitUI @FetchedResults one-many relationship didn't update properly

Viewed 50

I am using SwiftUI with Coredata to display a one to many relationship data elements.

Example:

One Group has many Book.

I have two views, GroupView has many GroupRowViews.

struct GroupView: View {

    var groups: FetchedResults<Group>

    var body: some View {
        ScrollView(.horizontal) {
            HStack(alignment: .center, spacing: 32, content: {

                ForEach(contractGroups) { group in
                    HStack {
                        GroupRowView(group: group)
                        Text(String(group.books?.count ?? 0)) // display correct
                                            .foregroundColor(Color.red)
                    }

                }

            })
        }
    }
}

and the GroupRowView is here:

struct GroupRowView: View {

    var group: Group

    var body: some View {
        ZStack {

            Color(.white)
            VStack {
                Text(group.name!)
                    .foregroundColor(Color.white)
                    .font(.system(size: 17, weight: .bold, design: .default))

                Text(String(group.books?.count ?? 0)) //display wrong
                    .foregroundColor(Color.white)
            }
        }.frame(width: 120, height: 100, alignment: .center)
    }
}

Every time when the books was updated, then the book count display correctly in the GroupView but not in the GroupRowView.

The group in forEach is FetchedResults<ContractGroup>.Element, is it the reason not the same as var group: ContractGroup in GroupRowView?

How to make the group.books in the GroupRowView get the changes?

Thanks!

1 Answers

You need to observe group in row explicitly, like

struct GroupRowView: View {

    @ObservedObject var group: Group

    // ... other code
Related