Delete row from Realm via SwiftUI occurs exception 'Object has been deleted or invalidated.'

242 Views Asked by At

I trying to delete row from SwiftUI list which load data from Realm DB, it's implemented like here:

struct MyView: View {
    private let realm = try! Realm()
    
    var body: some View {
            List {
                ForEach(realm.objects(MyModelDB.self)) { model in
                    MyRow(model: model)
                  }
                }.onDelete { indexSet in
                  try? realm.write {
                    indexSet.forEach { index in
                      realm.delete(words[index])
                    }
                  }
                }
            }
        }
    }
}

but when I perform deleting, I receive an exception:

*** Terminating app due to uncaught exception 'RLMException', reason: 'Object has been deleted or invalidated.'

Whats wrong?

1

There are 1 best solutions below

2
Jay On

A couple of options are: delete the objects in reverse order OR delete all of the objects at once.

Here's why. Suppose you have three objects

a  index 0
b  index 1
c  index 2

so the total count is 3 and your indexSet contains indexes 0 1 and 2.

If you were to iterate over that, there would be three loops, however, realm is live updating so if you delete the object at index 0, then only two indexes remain, so when it tries to perform the third loop, it will crash.

Deleting in reverse alleviates that issue as index 2 is deleted first, then index 1 and then index 0.

I would suggest gathering up the objects you want deleted into an array or list and then deleting them all at once without iterating

realm.delete(objects: Sequence>)

where Sequence would be an Array or List.