How to update @FetchRequest, when a related Entity changes in SwiftUI?

前端 未结 3 1210
时光说笑
时光说笑 2020-11-30 05:40

In a SwiftUI View i have a List based on @FetchRequest showing data of a Primary entity and the via relationship connecte

3条回答
  •  甜味超标
    2020-11-30 06:32

    You need a Publisher which would generate event about changes in context and some state variable in primary view to force view rebuild on receive event from that publisher.
    Important: state variable must be used in view builder code, otherwise rendering engine would not know that something changed.

    Here is simple modification of affected part of your code, that gives behaviour that you need.

    @State private var refreshing = false
    private var didSave =  NotificationCenter.default.publisher(for: .NSManagedObjectContextDidSave)
    
    var body: some View {
        List {
            ForEach(fetchedResults) { primary in
                NavigationLink(destination: SecondaryView(primary: primary)) {
                    VStack(alignment: .leading) {
                        // below use of .refreshing is just as demo,
                        // it can be use for anything
                        Text("\(primary.primaryName ?? "nil")" + (self.refreshing ? "" : ""))
                        Text("\(primary.secondary?.secondaryName ?? "nil")").font(.footnote).foregroundColor(.secondary)
                    }
                }
                // here is the listener for published context event
                .onReceive(self.didSave) { _ in
                    self.refreshing.toggle()
                }
            }
        }
        .navigationBarTitle("Primary List")
        .navigationBarItems(trailing:
            Button(action: {self.addNewPrimary()} ) {
                Image(systemName: "plus")
            }
        )
    }
    

提交回复
热议问题