Realm - Can't use object after having been deleted

后端 未结 2 1805
后悔当初
后悔当初 2021-01-06 11:13

I have a video player in my app. There is a list of videos in a collection view. If you tap on one of the cells, a new view controller appears to play the selected video. Al

2条回答
  •  生来不讨喜
    2021-01-06 11:44

    This one is definitely tricky for a number of architectural reasons.

    You're right in that you could simply remove the object from the FavoriteList.videos and then properly delete it from Realm when going to dismiss the controller, but you're right that if the user clicks the home button, or the app crashes before then, you'll end up with a headless video object. You would need to be able to make sure you can track that.

    There's a couple of things you might be able to consider.

    • Add an isDeleted property to the Video class. When the user unfavorites the video, remove the Video object from FavoriteList.videos, set that property to true, but leave it in Realm. Later on (either when the app quits or the view controller is dismissed), you can then do a general query for all objects where isDeleted is true and delete them then (This solves the headless problem).
    • Since your architecture requires a view controller relying on a model that could be deleted from under it, depending on how much information you're using from that Video object, it might be safer to make an unmanaged copy of the Video copy, and use that one to power the UI of the view controller. You can create a new copy of an existing Realm object by doing let unmanagedVideo = Video(value: video).

提交回复
热议问题