Search code examples
core-dataswiftui

Update CoreData relationship object in SwiftUI


I need your help about a SwiftUI/CoreData topic.

I have a Kid class containing a one-to-many relationship called parents that is a NSSet? of Parent objects.

I would like to access and be able to update properties of my parents relationship objects. I created a computed property parentsArray to get an array from the NSSet. Here is the code:

public var parentsArray: [Parent] {
    let set = parents as? Set<Parent> ?? []
    return set.sorted {
        $0.position < $1.position
    }
}

Now, let's go to my SwiftUI view:

ForEach(viewModel.kid.parentsArray) { parent in
    Section(header: Text("Parent \(parent.position)")) {
        TextField("Name", text: $parent.firstName) // Error: Cannot find $parent in scope                   
    }
}

As you can see, the problem is that I can't access to the binding $parent.firstName.

The ForEach loop local variable parent is of type Parent.

Can you help me ? Thanks a lot !


Solution

  • TextField expects Binding, but your calculable parentsArray provides CoreData objects.

    It is better to separate TextField into standalone view with observed Parent, like

    struct ParentView: View {
      @ObservedObject var parent: Parent    // allows binding 
    
      var body: some View {
         TextField("Name", text: $parent.firstName)
      }
    }
    

    and then use it in section, like

    ForEach(viewModel.kid.parentsArray) { parent in
        Section(header: Text("Parent \(parent.position)")) {
            ParentView(parent: parent) 
        }
    }