如何在onDelete中获取当前的CoreData项目 [英] How to get current CoreData item in onDelete
问题描述
有两个实体 Parent
和 Child
,这是一对多的关系.一个父母和多个孩子.
There two entities Parent
and Child
, which is one to many relationship. One Parent and many Child.
我使用 EditMode
删除 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])
}
}
}
当发生 onDelete
时,我还想更新 Parent
和 Child
实体的其他属性.但是我必须找到已删除的当前 Child
项.怎么做?
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?
感谢您的帮助.
推荐答案
这里是可行的方法...(假设您的.loadDB返回数组,但通常类似的方法适用于任何随机访问集合)
Here is possible approach... (assuming your .loadDB returns array, but in general similar will work with any random access collection)
使用Xcode 11.4(使用常规的项目数组)进行了测试
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)
}
}
这篇关于如何在onDelete中获取当前的CoreData项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!