有两个实体Parent和Child,它们是一对多的关系。一个父母多个孩子。
我使用EditMode删除Child数据,如:
@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)
}
}
}
}
}deleting方法在另一个类中定义,如下所示:
public func deleting(at indexset: IndexSet) {
CoreData.executeBlockAndCommit {
for index in indexset {
CoreData.stack.context.delete(self.fetchedObjects[index])
}
}
}我还想在发生Parent和Child实体时更新onDelete的其他属性。但是,我必须找到当前的Child 项目,该项目被删除了。怎么做?
谢谢你的帮助。
发布于 2020-06-02 14:27:37
这是可能的方法..。(假设您的.loadDB返回数组,但通常类似于任何随机访问集合)
用Xcode 11.4测试(使用常规项数组)
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
复制相似问题