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()
}
}

相关内容

最新更新