有两个实体 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])
}
}
}
而我也想更新其他的Attribute of Parent
和 Child
实体时 onDelete
发生。但我必须找到当前的 Child
被删除的项目. 怎么做呢?
谢谢大家的帮助。
这里是一个可能的方法......(假设你的.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)
}
}