SwiftUI-如何删除CoreData中实体中的行
我正在尝试开发一个应用程序,将值输入到列表中显示的实体中。但是当我从列表中删除它们时,它们不会在数据库中被删除。你有解决办法吗SwiftUI-如何删除CoreData中实体中的行,swift,xcode,core-data,swiftui,Swift,Xcode,Core Data,Swiftui,我正在尝试开发一个应用程序,将值输入到列表中显示的实体中。但是当我从列表中删除它们时,它们不会在数据库中被删除。你有解决办法吗 struct ViewList: View { @Environment(\.managedObjectContext) var context @State var newName: String = "" @FetchRequest( entity: ItProduct.entity(), sortDescr
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])
}
}
}
}
}
}
struct视图列表:视图{
@环境(\.managedObjectContext)变量上下文
@状态变量newName:String=“”
@获取请求(
实体:ItProduct.entity(),
sortDescriptors:[NSSortDescriptor(密钥路径:\ItProduct.name,升序:true)]
)变量列表:FetchedResults
var body:一些观点{
VStack{
HStack{
TextField(“我插入列表的名称”,text:$newName)
按钮(操作:{
如果self.newName!=''{self.add()}
}){Image(系统名:“plus”)}
}
名单{
ForEach(list,id:\.self){i在
视图项(产品:i)
}.onDelete{indexSet in
用于索引集中的索引{
self.context.delete(self.list[index])
}
}
}
}
}
}
好吧,如果设置正确,那么代码应该可以工作。除了如果您正在寻找应用程序启动之间的数据持久性,那么您需要在某个时间保存
CoreData
上下文
try? self.context.save()
解决方案:
嗯,如果设置正确,那么代码应该可以工作。
除了如果您正在寻找应用程序启动之间的数据持久性,那么您需要在某个时间保存
CoreData
上下文
try? self.context.save()
解决方案:
@MxM乐于帮助:)@MxM乐于帮助:)