ios - 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 本身中起作用。
非常感谢您对此的任何帮助和想法。谢谢...
解决方案
推荐阅读
- javascript - 使用 NETLIFY 表单时的电子邮件验证
- excel - 按颜色渐变的条件格式问题。谢谢
- python - 我应该使用什么方法对具有数千个类别的文本进行分类?
- ios - 何时创建新的 Apple 推送通知服务证书
- python - 在@njit 装饰函数中使用@jitclass 创建字典
- ios - 如何在 iOS 设备上获取所有(或选择一个)注册的电子邮件帐户(针对当前用户)
- javascript - 在中使用 .map标签 - react.js
- c++ - c++ 使用'auto'初始化结构的困难
- openlayers - 如何在 OpenLayers 6 中显示多个标记以及与它们相关联的单个 onclick 事件
- javascript - 使用 Map 类的 js Graph - 在哪里存储重量?