首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在CoreData中获取当前onDelete项

如何在CoreData中获取当前onDelete项
EN

Stack Overflow用户
提问于 2020-06-02 13:46:23
回答 1查看 111关注 0票数 1

有两个实体ParentChild,它们是一对多的关系。一个父母多个孩子。

我使用EditMode删除Child数据,如:

代码语言:javascript
运行
复制
@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方法在另一个类中定义,如下所示:

代码语言:javascript
运行
复制
public func deleting(at indexset: IndexSet) {

    CoreData.executeBlockAndCommit {

        for index in indexset {
            CoreData.stack.context.delete(self.fetchedObjects[index])
        }
    }
}

我还想在发生ParentChild实体时更新onDelete的其他属性。但是,我必须找到当前的Child 项目,该项目被删除了。怎么做?

谢谢你的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-02 14:27:37

这是可能的方法..。(假设您的.loadDB返回数组,但通常类似于任何随机访问集合)

用Xcode 11.4测试(使用常规项数组)

代码语言:javascript
运行
复制
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)
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62153505

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档