有两个实体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
项目。怎么做?
感谢您的帮助。
答案 0 :(得分:1)
这里是可行的方法...(假设您的.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)
}
}