Swift核心数据从属性列表中删除项目



我正在做一个核心数据项目。目前,我有一个实体(项目(具有以下属性:

@NSManaged public var title: String?
@NSManaged public var list: [String]

我正在使用带有ForEach的列表在列表中显示实体。如果用户选择一个项目,我会使用导航链接打开另一个视图。

主列表代码:

struct ItemList: View {
@Environment(.managedObjectContext) var viewContext
@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: Item.title, ascending: true)]) 
var ItemFetch: FetchedResults<Item>
var body: some View {
NavigationView {
List {
ForEach(ItemFetch, id: .self {item in
NavigationLink(destination: ItemView(Item: item) {
Text(item.title)
}
}
.onDelete(perform: removeItem(at:))
}
}
}
private func removeItem(at offsets: IndexSet) {
for index in offsets {
let item = ItemFetch[index]
viewContext.delete(item)
}
}
}

第二视图代码:

struct ItemView: View {
@Environment(.managedObjectContext) var viewContext
@ObservedObject var Item: Item
var body: some View{
NavigationView {
List {
ForEach { Item.list.indices { entry in
Text(self.Item.list[entry]
}
}
.navigationBarItem(
trailing:
Button(action: {
self.Item.list.append("SubItem")
}) {
Text("Add SubItem")
})
}
}
}

用户可以通过按下按钮将子项添加到列表中。

也可以通过滑动删除项目列表中的项目。

现在我希望用户也可以通过滑动删除子项目列表中的子项目。如果我试图实现相同的函数,那么用户将通过删除不是我想要的子项来删除项。

我不知道如何使用FetchRequest只获取名为list的属性。有没有这样做的方法或删除子项的其他方法?

谢谢。

问题中发布的代码实际上不起作用。

如果您希望能够对子项运行查询,则可能需要为它们创建一个新实体,并使用核心数据1对n关系链接这两个实体。

然而,如果你想坚持使用字符串数组来存储子项,你可以通过添加:来实现滑动删除功能

.onDelete(perform: removeSubItem(at:))

到ItemView中的ForEach,即

ForEach(Item.list, id: .self) { entry in // you should actually call it "item" to avoid confusion...
Text(entry)
}.onDelete(perform: removeSubItem(at:))

removeSubItem可能是这样的:

private func removeSubItem(at offsets: IndexSet) {
for index in offsets {
Item.list.remove(at: index)  // you should actually call it "item" to avoid confusion...
try? viewContext.save()
}
}

最新更新