在我的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本身中都可以使用。
在此方面的任何帮助和想法都非常感谢。谢谢...