首页 > 解决方案 > 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])
                    }
                }
            }
        }
    }
}

标签: swiftxcodecore-dataswiftui

解决方案


好吧,如果设置正确,那么您的代码应该可以工作。
除了...如果您正在寻找应用程序启动之间的数据持久性,在这种情况下,您需要CoreData在某个时间保存上下文。

try? self.context.save()

解决方案:

.onDelete { indexSet in
    for index in indexSet {
        self.context.delete(self.list[index])
        try? self.context.save()
    }
}

推荐阅读