0

我创建了一个保存在核心数据中的客户端列表。我通过 AddView 添加了一些属性,现在我尝试使用不同的视图添加新属性。为了做到这一点,我知道我需要使用observedObject 属性包装器,这样它就不会创建新客户端而是更新现有客户端。这是代码:

    import SwiftUI
import CoreData

struct TopicView: View {
   
@Environment(\.managedObjectContext) var managedObjectContext
let myStudent: StudentData
@ObservedObject var topic: StudentData
@State var content = ""
@State private var show = false

var body: some View {
    ZStack{
        RadialGradient(gradient: Gradient(colors: [.blue, .black]), center: .center, startRadius: 200, endRadius: 600)
            .ignoresSafeArea(.all)
        VStack{
    
    Text("My Students")
        .bold()
        .font(.system(size: 50, design: .rounded))
        .foregroundColor(.white)
        .padding(.top)
     Text("keep track of them")
        .italic()
        .foregroundColor(.white)
        .font(.system(size: 25, design:.serif))

    Image(systemName: "book")
    .resizable()
    .foregroundColor(.white)
    .frame(width: 80.0, height: 50.0)
        .padding(.bottom)
    }
}
                Section (header: Text("Topics covered")
                    .bold()
                    .padding(.all)
                    .font(.title3)) {
                    TextField("Add content", text: Binding(
                                get: { self.topic.content ?? ""},
                                set: { self.topic.content = $0 } )
                            )
                    //Text(topic.content ?? "")
            .padding()}
                    Button ("Save")
        { let newStudent = StudentData(context: self.managedObjectContext)
                        newStudent.content = self.topic.content
            try? self.managedObjectContext.save()
                        self.topic.content = ""
                    }.foregroundColor(.blue)
                    .cornerRadius(10)
                    .frame(width: 200, height: 50, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                    .font(.headline)
          Spacer()
                        }
    

}

我从不同的视图(StudentView)推送主题视图,但是由于我添加了observedObject,它在StudentView中引发了这个错误: 错误

我知道这很容易解决,但我在互联网上找不到太多信息。谢谢

4

0 回答 0