SwiftUI/Core Data:在从 .onDelete 修饰符调用的托管对象上下文上使用 Save() 时发生崩溃

Gol*_*ver 8 core-data ios swiftui swiftui-list

在我的 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)
                    }
                }
            }
Run Code Online (Sandbox Code Playgroud)

崩溃发生在调用 .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)
                    }
                }
            }
Run Code Online (Sandbox Code Playgroud)

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

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