在视图中更新CoreData中的数据及其值 [英] Update data in CoreData and its value in a view
问题描述
我是不熟悉使用Swift和CoreData进行开发的人.我一直在努力与以下代码一起使用,该代码显示一个视图,其中包含有关与CoreData存储的学生的一些信息.视图中显示的问问题"按钮会更新student.questionAskedClass,但视图不会更新其值.
I am new to developing in Swift and CoreData. I've been struggling with the following code which displays a view with some information on a student which is stored with CoreData. The button "Ask question" which is displayed in the view updates student.questionAskedClass but the view does not updates its value.
该值显然在内部进行了更新,因为如果我重新启动该应用程序,则可以看到该值已被更新.但我希望看到它实时更新.
The value is clearly updated internally because if I relaunch the application, I can see that the value has been updated. But I would like to see it updated live.
感谢您的帮助,弗朗索瓦(Francois)
Thanks for your help, Francois
import SwiftUI
struct StudentView: View {
@Environment(\.managedObjectContext) var managedObjectContext
var student: Student
var body: some View {
VStack(alignment: .leading) {
Text("\(student.firstName)").font(.headline).foregroundColor(Color.black)
Text("\(student.lastName)").font(.headline).foregroundColor(Color.gray)
Spacer().frame(height: 10)
Text("\(student.email)").font(.headline).foregroundColor(Color.gray)
Spacer().frame(height: 10)
Text("Number of questions asked: \(student.questionAskedClass)").font(.headline).foregroundColor(Color.gray)
Button(action: {
self.askQuestion()
}) {
Text("Ask question")
}
}
}
func askQuestion() {
self.managedObjectContext.performAndWait {
self.student.questionAskedClass += 1
try? self.managedObjectContext.save()
}
}
}
推荐答案
您需要的只是
struct StudentView: View {
@Environment(\.managedObjectContext) var managedObjectContext
@ObservedObject var student: Student // << here !!
通过Xcode 11.4/iOS 13.4测试
Tested with Xcode 11.4 / iOS 13.4
这篇关于在视图中更新CoreData中的数据及其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!