[Solved]Crash when using iterator on list of Objects: [RLMFastEnumerator retain]: message sent to deallocated instance


#1

So, I have a collectionViewController and detailViewController. Im passing an id of object from CVController to detail controller in order to retrieve it later. Here is the object of a class im passing:

class FilmCategory: Object {
    @objc dynamic var id = 0
    @objc dynamic var name = ""
    var films = List<Film>() 

override static func primaryKey() -> String? {
        return "id"
    }

and here is Film class:

class Film: Object {
    @objc dynamic var id = 0
    @objc dynamic var name = ""
    var actors = List<String>()
    @objc dynamic var imageURL = ""
    @objc dynamic var duration = 0


    override static func primaryKey() -> String? {
        return "id"
    }

Im initialising objects from JSON, everything is working fine, in my collectionViewController im able to retrieve all categories.
after I have passed id from CollectionViewController through segue, I need to iterate through films list ( var films = List() )

Here is how im trying to do it:

class DetailViewController: UIViewController {
    
    let realm = try! Realm()
    
    var currentCategoryIndex = Int()
    @objc dynamic var category: FilmCategory?
    
    @IBOutlet weak var filmTextLabel: UILabel!
    @IBOutlet weak var durationTextLabel: UILabel!
    @IBOutlet weak var ImageView: UIImageView!
    var films = List<Film>()
    var filmsIterator: List<Film>.Iterator!
    
    
    @IBAction func nextFilm(_ sender: UIButton) { nextFilm() }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        category = realm.object(ofType: FilmCategory.self, forPrimaryKey: currentCategoryIndex)
        navigationItem.title = category?.name ?? ""
        setupFilms()
    }
     
    private func setupFilms() {
        guard let category = category else { return }
        self.films = category.films
        if films.isEmpty {
            AlertController.alertAndReturnBack(viewController: self, title: "no films yet!", message: "This category is empty.")
        } else {
            self.filmsIterator = films.makeIterator()
        }
    }


    private func NextFilm() {
         while let nextObject = filmsIterator.next() { 
            filmTextLabel.text = nextObject.name
            durationTextLabel.text = "\(nextObject.duration)"
           // etc 
    }

every time im pressing pressing next button, Xcode yells at me because of Error:
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0

I used Zombie Objects to get more descriptive logs of error and now it shows this error: [RLMFastEnumerator retain]: message sent to deallocated instance 0x7f8ed3e63400

Unfortunately I don’t understand how to fix it(

I Solved it. in this line of code self.filmsIterator = films.enumerated().makeIterator()