Justin Baron
Justin Baron

Reputation: 11

Adding a deleted or invalidated object to a Realm is not permitted

I am trying to delete(truncate table) object and than adding it again, but getting this exception at runtime:

Adding a deleted or invalidated object to a Realm is not permitted

My code:

let realm = try! Realm()
let objFolder = realm.objects(FolderColor.self)
do{   
    try realm.write {
        realm.delete(objFolder)
        for obj in arrFolderColors {
            realm.add(obj)
        }
    }
}
catch{}

Upvotes: 1

Views: 2195

Answers (2)

Jay
Jay

Reputation: 35648

I like the other answer but I think what's going on here is you have a class var

@objc dynamic var folderColorResults = Results<FolderColor>

and at some point you've populated that var with some FolderColor objects

self.folderColorResults = realm.objects(FolderColor.self).filter("color == 'blue'")

So then, when you call the code in the question, it's deleting all of the FolderColor objects from Realm - when that happens, the folderColorResults results var is also getting updated (all objects removed).

Therefore there are no objects to write back out to disk.

Remember that Realm is a live database and Results objects are always keep in sync with the actual data; change an object on one place, it changes it everywhere that object is being used.

A suggested fix is to cast the folderColorResults to an Array.

let myArray = Array(self.folderColorResults)

which disconnects those objects from Realm and they will not be updated.

Of course, I could be totally wrong on this assumption so I can update further if more information is provided.

Upvotes: 2

TiM
TiM

Reputation: 15991

Realm objects are simply pointers to their data in the Realm database. When you call realm.delete, you completely delete the contents from memory and disk. The Realm object itself is still in memory, but you can’t call any properties or try and re-add it.

There’s a object.invalidated property you can use to check if an object has been deleted before you try and add it to Realm to avoid accidentally triggering that exception.

I’d recommend you rethink your logic to not need to call ‘realm.delete’. If it’s in an array, you can just remove it from the array but keep it in the database.

Upvotes: 1

Related Questions