swift - SwiftUI - 如何在 CoreData 中删除实体中的行
问题描述
我正在尝试开发一个应用程序来将值输入到列表中显示的实体中。但是当我从列表中删除它们时,它们并没有在数据库中删除。你有解决方案吗?
struct ViewList: View {
@Environment(\.managedObjectContext) var context
@State var newName: String = ""
@FetchRequest(
entity: ItProduct.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \ItProduct.name, ascending: true)]
) var list: FetchedResults<ItProduct>
var body: some View {
VStack {
HStack {
TextField("I insert the name of the list", text: $newName)
Button(action: {
if self.newName != "" {self.add()}
}) { Image(systemName: "plus")}
}
List {
ForEach(list, id: \.self) { i in
ViewItem(product: i)
}.onDelete { indexSet in
for index in indexSet {
self.context.delete(self.list[index])
}
}
}
}
}
}
解决方案
好吧,如果设置正确,那么您的代码应该可以工作。
除了...如果您正在寻找应用程序启动之间的数据持久性,在这种情况下,您需要CoreData
在某个时间保存上下文。
try? self.context.save()
解决方案:
.onDelete { indexSet in
for index in indexSet {
self.context.delete(self.list[index])
try? self.context.save()
}
}
推荐阅读
- c# - 如何解决空数据库表上的乐观并发异常错误
- postgresql - 使用 Postgresql 全文搜索模糊匹配所有搜索词
- javascript - 如何使用 vue-router 检查用户是否进入上一页?
- javascript - 如何从 websocket 连接中读取标头
- linux - 带有备份和删除的符号链接
- katalon-studio - 有没有办法创建“验证元素文本不是”关键字?
- gcc - gcc 的 Conda 安装以链接错误结束,加载共享库 libmpfr.so.4 时出错
- swift - Xcode 11 无法识别核心数据实体
- java - 由于外键关系 java.lang.IllegalArgumentException 无法持久化对象:对象不是声明类的实例
- amazon-web-services - 基础设施原语上下文中工作者和服务之间的区别