1

There two entities Parent and Child, which is one to many relationship. One Parent and many Child.

I use EditMode to delete Child data like:

@ObservedObject private var db = CoreDataDB<Child>(predicate: "parent")

var body: some View {

    VStack {
        Form {

            Section(header: Text("Title")) {
                ForEach(db.loadDB(relatedTo: parent)) { child in

                    if self.editMode == .active {
                        ChildListCell(name: child.name, order: child.order)
                    } else {
                        ...
                    }
                }
                .onDelete { indices in 
                  // how to know which child is by indices here ???
                  let thisChild = child // <-- this is wrong!!!

                  self.db.deleting(at: indices)
                }
            }
        }
    }
}

The deleting method is defined in another Class like:

public func deleting(at indexset: IndexSet) {

    CoreData.executeBlockAndCommit {

        for index in indexset {
            CoreData.stack.context.delete(self.fetchedObjects[index])
        }
    }
}

And I also want to update other Attribute of Parent and Child Entities when onDelete occurs. But I have to locate the current Child item which is deleted. How to make it?

Thanks for any help.

Muz
  • 699
  • 1
  • 11
  • 25

1 Answers1

1

Here is possible approach... (assuming your .loadDB returns array, but in general similar will work with any random access collection)

Tested with Xcode 11.4 (using regular array of items)

var body: some View {
    VStack {
        Form {
            Section(header: Text("Title")) {
                // separate to standalone function...
                self.sectionContent(with: db.loadDB(relatedTo: parent))
            }
        }
    }
}

// ... to have access to shown container
private func sectionContent(with children: [Child]) -> some View {
    // now we have access to children container in internal closures
    ForEach(children) { child in

        if self.editMode == .active {
            ChildListCell(name: child.name, order: child.order)
        } else {
            ...
        }
    }
    .onDelete { indices in

        // children, indices, and child by index are all valid here
        if let first = indices.first {
            let thisChild = children[first]       // << here !!
            // do something here
        }

        self.db.deleting(at: indices)
    }
}
Muz
  • 699
  • 1
  • 11
  • 25
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • could you help me check the question https://stackoverflow.com/questions/62860449/crash-occurs-when-executing-share-extension-twice-in-system-files-to-share-file. It troubles me a long time. Thanks anyway. – Muz Jul 14 '20 at 15:28