我创建了一个保存在核心数据中的客户端列表。我通过 AddView 添加了一些属性,现在我尝试使用不同的视图添加新属性。为了做到这一点,我知道我需要使用observedObject 属性包装器,这样它就不会创建新客户端而是更新现有客户端。这是代码:
import SwiftUI
import CoreData
struct TopicView: View {
@Environment(\.managedObjectContext) var managedObjectContext
@Environment (\.presentationMode) var presentationMode
@ObservedObject var topic: StudentData
@State var content = ""
@State private var show = false
@StateObject private var keyboard = Keyboard()
var body: some View {
Form{
Section (header: Text("Topics covered")
.bold()
.padding(.all)
.font(.title3)) {
TextEditor(text: Binding(
get: {self.topic.content ?? ""},
set: {self.topic.content = $0 } ))
.frame(height: 250)
}
}.onTapGesture {
hideKeyboard()
}
}
}
Button ("Submit")
{
self.topic.content = self.content
self.topic.objectWillChange.send()
try? self.managedObjectContext.save()
self.presentationMode.wrappedValue.dismiss()
}.foregroundColor(.white)
这是应该显示新属性的视图:
import SwiftUI
import CoreData
import MapKit
struct StudentView: View {
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(entity: StudentData.entity(),
sortDescriptors: [],
animation: .spring()) var content: FetchedResults<StudentData>
@Environment (\.presentationMode) var presentationMode
@ObservedObject var topic: StudentData
@State var showModalView = false
@State private var showingSheet = false
let myStudent: StudentData
var body: some View {
NavigationView {
VStack{
Text("Topics Covered")
.font(.system(size: 30, weight: .bold, design: .rounded))
.foregroundColor(.red)
.padding(.horizontal)
Text("\(myStudent.content ?? "")")
.font(.title2)
.bold()
.foregroundColor(.white)
.padding(.horizontal) }}
Spacer()
Spacer()
}.sheet(isPresented: $showModalView, content: {
TopicView(topic: topic)})
问题是,如果我在文本编辑器中输入一些文本而不保存它,那么它会在另一个视图中正确显示。但是,当我保存它时,它不会显示在其他视图中。我的保存代码有什么问题吗?