无法解决在我的应用程序中删除笔记的问题。当我删除一条笔记时出现问题,应用程序有时会崩溃(例如,如果我添加了 3 个笔记并删除了第一个,然后它崩溃了),但碰巧我添加了多个笔记,我可以删除它们而无需任何问题。我不知道问题出在哪里,所以请求您的帮助。
查看模型
func deleteNote(atIndex index: Int) {
guard notes.indices.contains(index) else { return }
do {
let realm = try Realm()
try realm.write {
// Improved approach: Get object reference from results to avoid invalidation
if let objectToDelete = realm.objects(Note.self).filter("id == %@", notes[index].id).first {
realm.delete(objectToDelete)
// Remove from in-memory list after successful deletion in Realm
notes.remove(at: index)
} else {
print("Note not found in Realm for deletion (index: \(index))")
}
}
} catch {
print("Error deleting note: \(error.localizedDescription)")
}
}
通过滑动 .onDelete 删除笔记。代码:
.onDelete(perform: { indexSet in
guard let index = indexSet.first else { return }
viewModel.deleteNote(atIndex: index)
})
**Error:** Exception NSException * "Object has been deleted or invalidated." 0x0000600000ca6ac0
name __NSCFConstantString * "RLMException" 0x0000000105ad44e0
reason __NSCFString * "Object has been deleted or invalidated." 0x00006000017a3280
userInfo __NSDictionaryM * 2 key/value pairs 0x000060000054fd00
reserved __NSDictionaryM * 2 key/value pairs 0x000060000054fcc0
我的猜测是错误发生在这一行realm.delete(objectToDelete)
func getNotes() {
let realm = try! Realm() // Get a Realm instance
notes = Array(realm.objects(Note.self)) // Fetch all notes from Realm
}
List {
ForEach(viewModel.notes) { note in
HStack {
Toggle(isOn: Binding(
get: { note.isCompleted },
set: { newValue in
viewModel.markNoteAsCompleted(id: note.id)
}
), label: {
Text(note.title)
.strikethrough(note.isCompleted)
.foregroundStyle(note.isCompleted ? Color("grey") : Color("white"))
})
.toggleStyle(iOSCheckboxToggleStyle())
}
.padding(10)
.listRowBackground(Color("backgroundLightSecond"))
}
.onDelete(perform: { indexSet in
guard let index = indexSet.first else { return }
viewModel.deleteNote(atIndex: index)
})
.listRowSeparator(.hidden)
}
.listRowSpacing(10)
.clipShape(.rect(cornerRadius: 15))
//.listStyle(.plain)
// .background(Color("background"))
.scrollContentBackground(.hidden)
当您调用
deleteNotes
时,在您要删除 Realm 对象的方法内:
realm.delete(objectToDelete)
下一行,您试图删除刚刚从数组中删除的对象,这会导致崩溃。
notes.remove(at: index)
您应该使用
@ObservedResults
属性包装器,而不是创建 Realm 对象数组。这可以帮助您观察结果集合。但它的目的是在 SwiftUI 视图中使用!
用法相当简单,如下所示:
struct ContentView: View {
@ObservedResults(Note.self) private var notes
var body: some View {
List {
ForEach(notes) { note in
// Code for view-cell customization
}
.onDelete($notes.remove)
}
}
}
您可能已经注意到,它允许您通过调用
$notes.remove
修饰符中的 onDelete()
来删除一行中的对象。
您可以在 Realm 的文档
上了解有关 @ObservedResults 的更多信息