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.
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()
}
}
}