ios - 如何在 onDelete 中获取当前的 CoreData 项

标签 ios core-data swiftui

有两个实体ParentChild ,这是一对多的关系。一位 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/

相关文章:

ios - 处理 Core Data 保存错误(Cocoa 错误 1570.)的方法

swiftui - 点击 NavigationLink 后如何执行操作?

swift - 如何使用 UIViewControllerRepresentable 在 SwiftUI 中呈现 UICollectionView

ios - 即使使用 set delegate,MKMapview delegate 也从未被调用

iphone - 隐藏 UITableviewcell 的 UIButton

ios - 从一对多关系中删除一个对象

ios - NSFetchedResultsController 未在委托(delegate)中调用controllerDidChangeContent

ios - SwiftUI:如何在没有 AppDelegate 的情况下强制景观

iOS 8 CLLocationManager

ios - UIimage 到 char* 转换