【问题标题】:SwiftUI - How to delete row in Entity in CoreDataSwiftUI - 如何在 CoreData 中删除实体中的行
【发布时间】:2020-04-22 19:48:58
【问题描述】:

我正在尝试开发一个应用程序来将值输入到列表中显示的实体中。但是当我从列表中删除它们时,它们并没有在数据库中删除。你有解决办法吗?

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

【问题讨论】:

    标签: swift xcode core-data swiftui


    【解决方案1】:

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

    try? self.context.save()
    

    解决办法:

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

    【讨论】:

    • @MxM 很高兴为您提供帮助 :)
    猜你喜欢
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2020-06-21
    相关资源
    最近更新 更多