Search code examples
core-dataswiftuiswiftui-form

Prefilling a SwiftUI form with values from CoreData in EditView


I have a EditView that gets send a "Person" saved by CoreData.

import SwiftUI
import CoreData

struct EditPersonView: View {
    @Environment(\.managedObjectContext) var moc
    @Environment(\.presentationMode) var presentationMode
    @ObservedObject var person: Person

    var body: some View {
        NavigationView {
            Form {
                Section {
                    TextField("Name", text: self.$person.name) // this does not work
                    Toggle(isOn: self.$person.isHome) { // this works
                        Text("Is home")
                    }
                }
                Section {
                    Button("Save") {
                        try? self.moc.save()
                        self.presentationMode.wrappedValue.dismiss()
                    }
                    .disabled(self.name.isEmpty)
                    Button("Cancel") {
                        self.presentationMode.wrappedValue.dismiss()
                    }
                }
            }
            .navigationBarTitle("Edit Person")
        }
    }
}

The value for "is home" gets initialized correctly from the value from CoreData, I can change and save it and it is fine.

My problem is the name attribute. I get the following error: "Cannot convert value of type 'Binding' to expected argument type 'Binding' "

What am I doing wrong?


Solution

  • The answer is found here:

    https://www.hackingwithswift.com/books/ios-swiftui/creating-nsmanagedobject-subclasses

    After creating my own NSManagedObject Subclass and removing the optional it worked.

    Another answer if you want to keep using the Class definition of CoreData: https://forums.swift.org/t/promoting-binding-value-to-binding-value/31055