Using SwiftUI, Core Data, and one-to-many relationships, why does the list not update when adding a row on the Many side

后端 未结 3 1993
我在风中等你
我在风中等你 2021-01-22 12:18

I have a SwiftUI project with Core Data. The data model is a simple one-to-many and two primary views which each have a textfield at the top and a button to add a new item to th

3条回答
  •  再見小時候
    2021-01-22 12:55

    The only thing I could come up with as a way to make it work decently well was to create a new FetchRequest for the Many items using the selected One in a predicate. Adding the FetchRequest and an init to the beginning of the OneDetailView allows for the list to update.

    struct OneDetailView: View {
    @Environment(\.managedObjectContext) var moc
    
    @ObservedObject var one: One
    
    @State private var newManyAttribute = ""
    @Binding var isNavTitleHidden: Bool
    
    @FetchRequest var manys: FetchedResults
    
    init(one: One, isNavTitleHidden: Binding) {
        self.one = one
        self._isNavTitleHidden = isNavTitleHidden
        var predicate: NSPredicate?
        predicate = NSPredicate(format: "one = %@", one)
        self._manys = FetchRequest(
            entity: Many.entity(),
            sortDescriptors: [],
            predicate: predicate
        )
    }
    
    var body: some View {
        VStack {
            HStack {
                TextField("New Many", text: self.$newManyAttribute)
                Spacer()
                Button(action: {
                    let newMany = Many(context: self.moc)
                    newMany.attribute = self.newManyAttribute
                    self.newManyAttribute = ""
                    self.one.addToMany(newMany)
                    try? self.moc.save()
                }) {
                    Image(systemName: "plus.circle.fill")
                        .foregroundColor(.green)
                        .frame(width: 32, height: 32, alignment: .center)
                }
            }
            .padding(.top)
            .padding(.horizontal)
    
            List {
                Section(header: Text("Manys")) {
                    ForEach(self.manys, id: \.self) { many in
                        ManyView(many: many).environment(\.managedObjectContext, self.moc)
                    }
                }
            }
        }
        .navigationBarTitle("\(self.one.wrappedName) Details")
        .onAppear {
            self.isNavTitleHidden = false
        }
    }}
    

提交回复
热议问题