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