有两个实体Parent
和 Child
,这是一对多的关系。一位 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
被删除的项目 .怎么做?谢谢你的帮助。
最佳答案
这是可能的方法...(假设您的 .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)
}
}
关于ios - 如何在 onDelete 中获取当前的 CoreData 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62153505/