Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
847 views
in Technique[技术] by (71.8m points)

core data - CoreData: why not refresh UI when book.isPublic toggled

'@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()
        }
    }
}
question from:https://stackoverflow.com/questions/65650902/coredata-why-not-refresh-ui-when-book-ispublic-toggled

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...