CoreData: why not refresh UI when book.isPublic toggled

后端 未结 1 1156
孤城傲影
孤城傲影 2021-01-27 04:33

\'@Environment(.managedObjectContext) var context\' will monitor the changes of context. When I click the button to toggle isPublic, I think it will cause to UI refreshing, Butt

相关标签:
1条回答
  • 2021-01-27 05:18

    You need to observe a Book changes via ObservedObject wrapper, like

    struct BookInfoView: View {
        @Environment(\.managedObjectContext) var context
        @ObservedObject var book: Book
        
        var body: some View {
            print("refresh"); return
                Group {
                    Button(action: onPublicToggled) {
                        Text(book.isPublic ? "private" : "public")
                    }
                }
        }
        
        func onPublicToggled() {
            context.perform {
                book.isPublic.toggle()
                try? context.save()
            }
        }
    }
    

    Note: @Environment(\.managedObjectContext) var context relates to context itself, not to your CoreData objects.

    0 讨论(0)
提交回复
热议问题