gpt4 book ai didi

core-data - 更新 Core Data 中的数据及其在 View 中的值

转载 作者:行者123 更新时间:2023-12-04 09:45:57 25 4
gpt4 key购买 nike

我是 Swift 和 CoreData 开发的新手。我一直在努力使用以下代码,该代码显示一个 View ,其中包含与 CoreData 一起存储的学生的一些信息。 View 中显示的“提问”按钮会更新 student.questionAskedClass 但 View 不会更新其值。

该值在内部显然已更新,因为如果我重新启动应用程序,我可以看到该值已更新。但我希望看到它实时更新。

谢谢你的帮助,
弗朗索瓦

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 测试

关于core-data - 更新 Core Data 中的数据及其在 View 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62108556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com