user3225917
user3225917

Reputation: 3021

Realm - Can I save a object after delete the object?

I want to add an object to favorites. In that case, when users press a button to add an object to favorites, the object will be saved to realm. then he press a button to remove the object from favorites and it will be removed. Afterwards, he press the button to save again, it should be saved again. Is it available?

When I pressed the save button twice, it says

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

The codes are like below.

func delete() {
realm.write({
    self.realm.delete(obj)
})
}
func save() {
    realm.write({
        self.realm.add(obj, update: false)
    })
}

Upvotes: 3

Views: 1719

Answers (1)

TiM
TiM

Reputation: 15991

(Disclaimer: I work for Realm)

Nope! Like it says on the tin, when an object has been deleted from a Realm, you can't simply use the same object reference to add it again.

It might be necessary to re-think your logic there. If the user has the opportunity to re-add the object after they've moved to delete it, it might be a good idea to not actually delete it, until the user has progressed the app to the point where they can't go back.

Failing that, you can always just save the information in the object, and simply create a new object when the user presses the button again.

Upvotes: 6

Related Questions