‘RLMException’, reason: ‘Object has been deleted or invalidated.’ [iOS] [Realm]

‘RLMException’, reason: ‘Object has been deleted or invalidated.’ [iOS] [Realm]

Are you fetching datas from server and just converting it to realm object without saving in local database. And at certain action, for example, click favorite button, you want to store that object to realm database?

Well, you might have done that. But once you do that, and try to unfavorite the items, now you will the issue as below.

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

So, what is going on with realm? Why is it crashing the app for the object which we haven’t store locally? Well, I was surprised too initially. But finally figure out what was going wrong.

First thing is, once you convert your json data to realm object, it create an instance which is yet not connected to database. But when you try to save that object to local database with that same object, Realm will track that object referencing. So after the object is stored, your object and realm database get connected.

At the time when you delete from local database, the reference will break, and even though you have the data, Realm will flag it as Invalid object. This is the reason behind the issue. So, that is the solution here.

Well, its easy. Instead of passing Json to realm object to be created, let’s first copy the object and then store the cloned one. You can use following code to copy the object.

let copy = realm.create(YourClass.self, value: OldObject, update: .all)
realm.add(copy, update: .all)

Now, you can pass copy object to store it in local database. This should fix your issue.

I hope you got to know something. Let me know if you are confused on this explanation. I will be happy to assist.

Thank you

Leave a Reply

santoshm