CoreData: why not refresh UI when book.isPublic toggled

為{幸葍}努か 提交于 2021-02-05 07:46:36

问题


'@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, Button text will change, But not, WHY?

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

回答1:


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.



来源:https://stackoverflow.com/questions/65650902/coredata-why-not-refresh-ui-when-book-ispublic-toggled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!