简体   繁体   中英

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)
    })
}

(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM