ios - 当 ForEach 中发生 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(perform: self.db.deleting)   <--- How to update CoreData when delete occurs in this line
            }
        }
    }
}
deleting方法在另一个类中定义,例如:
public func deleting(at indexset: IndexSet) {

    CoreData.executeBlockAndCommit {

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

我还想更新 Parent 的其他属性和 Child实体当onDelete发生。怎么做?

谢谢你的帮助。

最佳答案

这是可能的方法

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 
      // make other update here ...

      self.db.deleting(at: indices)

      // ... or here
    }
}

关于ios - 当 ForEach 中发生 onDelete 时如何更新其他 CoreData?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62142837/

相关文章:

ios - ReactiveCocoa 3 : Map signal to value (Swift)

ios - 从 CMBlockBuffer 中提取 h264

swift - 将 gif 存储在核心数据中 - Swift 3

ios - 核心数据:导入大型数据集

ios - 如果未显示所有 NavigationLink,则 NavigationView 中 SwiftUI 的 NavigationLink `tag` 和 `selection` 将停止工作

toggle - SwiftUI - 开关的使用 - 控制台日志 : “invalid mode ' kCFRunLoopCommonModes'” - didSet does not work

ios - swift 'does not have a member named'

iphone - CoreData 有什么不同

SwiftUI:缩放 View 中的形状

ios - 如何检测 iOS UIWebView 中的重定向