ios - 从带有部分的 SwiftUI 列表中删除 CoreData

标签 ios swift iphone core-data swiftui

目标

我想从列表中 ForEach 上的 SectionedFetchRequest 中删除一个项目。我发现的唯一解决方案是常规 FetchRequest 我已设法将其从 UIList 中删除,但没有从 CoreData 的 ViewContext 中删除。

我的问题很独特,因为我试图从不同于 FetchRequest 的 SectionedFetchRequest 中删除

    @SectionedFetchRequest(entity: Todo.entity(), sectionIdentifier: \.dueDateRelative, sortDescriptors: [NSSortDescriptor(keyPath: \Todo.dueDate, ascending: true)], predicate: nil, animation: Animation.linear)
    var sections: SectionedFetchResults<String, Todo>
    var body: some View {
        NavigationView {
            List {      
                ForEach(sections) { section in
                    Section(header: Text(section.id.description)) {
                        ForEach(section) { todo in
                            TodoRowView(todo: todo)
                                .frame(maxWidth: .infinity)
                                .listRowSeparator(.hidden)
                        }
                        .onDelete { row in
                            deleteTodo(section: section.id.description, row: row)
                            }
                        }

                    }
                }
    func deleteTodo(section: String, row: IndexSet) {
        // Need to delete from list and CoreData viewContex.
    }
// My old way of deleting notes with a regular fetch Request
func deleteNote(at offsets: IndexSet) {
    for index in offsets {
        let todo = todos[index]
        viewContext.delete(todo)
    }
    try? viewContext.save()
}

最佳答案

这就是您使用链接的方式...

将此添加到 TodoRowView(todo: todo)

.swipeActions(content: {
    Button(role: .destructive, action: {
        deleteTodo(todo: todo)
    }, label: {
        Image(systemName: "trash")
    })
})

而你需要在View

中使用这个方法
public func deleteTodo(todo: Todo){
    viewContext.delete(todo)
    do{
        try viewContext.save()
    } catch{
        print(error)
    }
}

或者您可以使用当前设置,该设置在 ForEach

上使用 onDelete
.onDelete { indexSet in
    deleteTodo(section: Array(section), offsets: indexSet)
    }

使用这种方法

func deleteTodo(section: [Todo], offsets: IndexSet) {
    for index in offsets {
        let todo = section[index]
        viewContext.delete(todo)
    }
    try? viewContext.save()
}

当然,要让其中任何一个工作,你需要一个工作

@Environment(\.managedObjectContext) var viewContext

在文件的顶部

关于ios - 从带有部分的 SwiftUI 列表中删除 CoreData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70399514/

相关文章:

ios - 检查 UIButton 图像

ios - 在 UICollectionView 中为单元格设置边界和调整大小

swift - 如何更改 .sheet 修饰符的过渡?

json - 使用参数 Swift 从 URL 获取数据

iphone - 你能用 Storyboard制作高级用户界面吗?

iphone - iOS/iPhone 上的正常运行时间卡住

ios - UIButton 半透明边框

ios - 如何保存录制的音频 iOS?

iphone - 更改数据编码

iphone - 重新排列 NSArray 和 NSDictionary 条目