首页 > 解决方案 > SwiftUI/Core Data:在从 .onDelete 修饰符调用的托管对象上下文上使用 Save() 时崩溃

问题描述

在我的 SwiftUI 应用程序中,我有一个 .onDelete SwiftUI 修饰符(在导航视图、列表、ForEach、链接等中),我用它来滑动删除核心数据实体对象。一切都很好,直到删除核心数据对象。当我在托管对象上下文上调用 .Save() 时发生崩溃。一直在拉我的头发试图找出原因。这是代码的快照:

        List {
            ForEach(claims, id: \.self.id) {(tmpClaim: Claim) in
                NavigationLink(destination: EditClaimView(passedClaim: tmpClaim, uuidString: tmpClaim.id.uuidString)) {
                    HStack {
                        VStack(alignment: .leading, spacing: 5) {
                            Text(tmpClaim.providerName)
                                .font(.headline)
                            Text("\(tmpClaim.serviceDate, formatter: DateFormatter.editing)")
                                .font(.footnote)
                        }
                        Spacer()
                        Text("\(String(describing: tmpClaim.serviceAmount).currencyFormatting())")
                    }
                    .contextMenu {
                        Button(action:
                            {
                                // code to create a new claim is here
})
                            {
                                Text("Duplicate")
                                Image(systemName: "doc.on.doc")
                            }
                    }
                }
            }
            .onDelete { indexSet in
                for index in indexSet {
                    (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext.delete(self.claims[index])
                }
if (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext.hasChanges {
                    do {
                        try (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext.save()
                    } catch {
                        print(error.localizedDescription)
                    }
                }
            }

调用 .save() 时发生崩溃,并且没有给出错误文本或消息。如果我将 save() 调用移至另一个修饰符 .OnDisappear() SwiftUI 修饰符,则不会发生崩溃:

.onDelete { indexSet in
                for index in indexSet {
                    (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext.delete(self.claims[index])
                }
            }

.onDisappear() {
                if (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext.hasChanges {
                    do {
                        try (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext.save()
                    } catch {
                        print(error.localizedDescription)
                    }
                }
            }

此外,已尝试将其放入函数中并抽象为该函数并从 .onDelete() 修饰符调用函数等。因此,同时使用 .OnDelete() 和 .onDisppear() 似乎可以工作,只是稍微延迟了保存,但我认为它应该在 .onDelete 本身中起作用。

非常感谢您对此的任何帮助和想法。谢谢...

标签: ioscore-dataswiftuiswiftui-list

解决方案


推荐阅读