Q1: Can '@Environment(.managedObjectContext) var context' monitor the changes of context? If not, it's just a method to get a value from environment, can I remove it, using CKDBManager.shared.context instead?
Q2: How can I refresh UI if some CoreData objects changed. One case is CoreData: why not refresh UI when book.isPublic toggled, the other two are following, how to fix them?
struct BookInfoView: View {
@Environment(.managedObjectContext) var context
var mySubscribe: Subscribe? {
guard let subscribes = book.subscribes as? Set<Subscribe> else { return nil }
return subscribes.first { $0.user?.id == Manager.shared.myId }
}
var isHidden: Bool {
guard let subscribe = mySubscribe else { return false }
return subscribe.isHidden
}
var isSubscribed: Bool {
guard let subscribe = mySubscribe else { return false }
return subscribe.isSubscribed
}
@ObservedObject var book: Book
let viewType: ViewType
var body: some View {
print("refresh"); return
VStack {
Button(action: onHiddenToggled) {
Text(isHidden ? "show" : "hide")
}
Button(action: onSubscribeToggled) {
Text(isSubscribed ? "unsub" : "sub")
}
}
}
func onHiddenToggled() {
guard let subscribe = mySubscribe else { return }
// let ckdbManager = CKDBManager.shared
// let context = ckdbManager.context
context.perform {
subscribe.isHidden.toggle()
try? context.save()
}
}
func onSubscribeToggled() {
guard let subsribes = book.subscribes as? Set<Subscribe> else { return }
let manager = Manager.shared
// let ckdbManager = CKDBManager.shared
// let context = ckdbManager.context
context.perform {
if let subscribe = subsribes.first(where: { $0.user?.id == manager.myId }) {
subscribe.isSubscribed.toggle()
try? context.save()
} else {
guard let myId = manager.myId else { return }
let request: NSFetchRequest<User> = User.fetchRequest()
request.predicate = NSPredicate(format: "id == %@", myId)
guard let users = try? context.fetch(request), let user = users.first else { return }
let subscribe = Subscribe(context: context)
subscribe.book = book
subscribe.user = user
subscribe.subscribeAt = Date()
subscribe.isHidden = false
subscribe.isSubscribed = true
try? context.save()
}
}
}
question from:
https://stackoverflow.com/questions/65651482/coredata-why-not-refresh-ui-if-buttons-clicked 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…