Search code examples
core-dataswiftuiobservedobject

Core Data observed object in SwiftUI


I have created a list of clients which get saved in core data. I added some attributes through an AddView and now I am trying to add a new attribute using a different view. In order to do that I understood I need to use the observedObject property wrapper so that it doesn't create a new client but update the existing one. This is the code:

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 {
Section (header: Text("Topics covered")
                        .bold()
                        .padding(.all)
                        .font(.title3)) {
                       TextField("Add content", text: $topic.content ?? "") //error here
                        //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()
                            }
        
    
}

I get two errors saying: Cannot convert value of type 'Binding<String?>' to expected argument type 'Binding' and Cannot convert value of type 'String' to expected argument type 'Binding<String?>'

It might be an easy fix but as I am still learning I can't get my head around it. Thanks


Solution

  • Thank you all, This is what I found and seems to work:

    TextField("Add content", text: Binding(
                                    get: { self.topic.content ?? ""},
                                    set: { self.topic.content = $0 } )
                                )