Realm - Can't use object after having been deleted

后端 未结 2 1804
后悔当初
后悔当初 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).
    0 讨论(0)
  • 2021-01-06 11:52

    Here is the workaround solution. Check if it works.

     class PlayerViewControllerr: UIViewController {
    
              var arrayForIndex = [Int]()
              var videos = List<Video>()
    
    
              @IBAction func didToggleStarButton(_ sender: UIButton) {
                   self.arrayForIndex.append(currentIndexInVideosList)     
               }
    
             @overide func viewWillDisappear(_ animated : Bool){
                  super.viewWillDisappear(animated)
                  for i in arrayForIndex{
                     let realm = try! Realm()
            try! realm.write {
                let videoToDelete = videos[i] /// Get the video that is currently playing
                realm.delete(videoToDelete)
            }
           }
            }
    
    0 讨论(0)
提交回复
热议问题