【问题标题】:SwiftUI and lists with coreData, unexpected behavior, why it delete another row, not I selectedSwiftUI 和带有 coreData 的列表,意外行为,为什么它删除另一行,而不是我选择
【发布时间】:2020-12-22 22:56:49
【问题描述】:

我有关于 onDelete{} 的问题。当我尝试从包含 coreData 数据的列表中删除单行时,它删除了上面的行,而不是我想要的行。 ViewModel 包含数组

 @ObservedObject var delegate = ViewModel()

            ForEach(delegate.notes) { note in
                VStack(alignment:.leading){
                Text(note.toDo!)
                Text(note.datee!)
                    .font(Font.system(size: 9))
                    .foregroundColor(.gray)
                    
                }
            }.onDelete(perform: removeNote)`

 @FetchRequest(
    entity: Note.entity(),
    sortDescriptors: [
        NSSortDescriptor(keyPath: \Note.toDo, ascending: true),
    ]
)
var notes : FetchedResults<Note>
func removeNote(offsets: IndexSet){
    for index in offsets{
        let note = notes[index]
   //     delegate.context.perform {
   
        delegate.context.delete(note)
        do{
            try delegate.context.save()
            delegate.refresh()
        }catch{}
      //  }
    }

【问题讨论】:

  • 更多细节:当我把第一个笔记和第二个笔记,然后我删除第一个,再放一个然后删除最新的一个coreData删除第二个而不是第三个笔记我想删除
  • delegate.refresh() 是做什么的?为什么一定要刷新?当笔记被删除时,SwiftUI 会自动将其从显示中移除。你不必有什么特别的。你可以评论delegate.refresh() 并尝试吗?还有一点小建议不要叫delegate
  • 完成上述操作后,还要在模型func delete(notes: [Note]) 中创建一个函数。让模型在处理任何核心数据对象时删除和使用context.perform / context.performAndWait
  • 当我注释掉 delegate.refresh() -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray"
  • 当我注释掉 delegate,refresh() 并执行 context.performAndWait 时,它起作用了,但列表仍未刷新。我必须离开笔记视图并再次访问它。

标签: swift core-data swiftui


【解决方案1】:
  @FetchRequest(
    sortDescriptors: [NSSortDescriptor(keyPath: \Note.toDo, ascending: true)],
    animation: .default)
var notes : FetchedResults<Note>
 private func removeNote(offsets: IndexSet) {
    withAnimation {
        offsets.map { notes[$0] }.forEach(delegate.context.delete)

        do {
            try delegate.context.save()
        } catch {
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    • 2022-01-20
    • 2016-09-11
    • 1970-01-01
    • 2020-02-29
    • 2021-02-01
    • 1970-01-01
    相关资源
    最近更新 更多