How to get current CoreData item in onDelete

北慕城南 提交于 2020-06-17 06:22:24

问题


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.


回答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)
    }
}


来源:https://stackoverflow.com/questions/62153505/how-to-get-current-coredata-item-in-ondelete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!