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

前端 未结 3 1207
时光说笑
时光说笑 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条回答
  •  Happy的楠姐
    2020-11-30 06:21

    I also struggled with this and found a very nice and clean solution:

    You have to wrap the row in a separate view and use @ObservedObject in that row view on the entity.

    Here's my code:

    WineList:

    struct WineList: View {
        @FetchRequest(entity: Wine.entity(), sortDescriptors: [
            NSSortDescriptor(keyPath: \Wine.name, ascending: true)
            ]
        ) var wines: FetchedResults
    
        var body: some View {
            List(wines, id: \.id) { wine in
                NavigationLink(destination: WineDetail(wine: wine)) {
                    WineRow(wine: wine)
                }
            }
            .navigationBarTitle("Wines")
        }
    }
    

    WineRow:

    struct WineRow: View {
        @ObservedObject var wine: Wine   // !! @ObserveObject is the key!!!
    
        var body: some View {
            HStack {
                Text(wine.name ?? "")
                Spacer()
            }
        }
    }
    

提交回复
热议问题