MarksCode
MarksCode

Reputation: 8604

viewController not being removed properly?

In my viewController I have an NSFetchedResultsController for populating a tableView. In the viewDidLoad() I'm saving the current time to a variable, then printing it out in the NSFetchedResultsController's didChange AnyObject callback:

class MyViewController: UIViewController, NSFetchedResultsControllerDelegate {
    var date: Date!
    var fetchedResultsController: NSFetchedResultsController<Event>!
   
    override func viewDidLoad() {
        super.viewDidLoad()
        date = Date()
    }

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
        switch type {
        case .insert:
            feedTable.insertRows(at: [newIndexPath!], with: .fade)
            print(date)
        default:
            break
    }
}

I noticed that when I leave this view then come back this callback is called twice and the date from the first time I was in the view is printed as well as the new one:

2017-05-14 18:29:42 +0000

2017-05-14 18:30:01 +0000

I'm leaving the view in a seperate function like this:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "HomePage") as? HomeVC
controller?.managedObjectContext = self.managedObjectContext
self.present(controller!, animated: true, completion: nil)

Why does this MyViewController seem to stick around even after I leave it and come back? Is the way I'm leaving it not removing it properly?

Upvotes: 0

Views: 94

Answers (2)

Nebojsa Nadj
Nebojsa Nadj

Reputation: 641

What do you mean by "leave the view" Are you going back? If you are, then deinit is not being called.

Test it by doing the following.

deinit {
   print("VC Should deinitialize")
}

If this isn't called when you go back, then you have a retain cycle problem.

Upvotes: 0

matt
matt

Reputation: 535925

I'm leaving the view in a seperate function like this:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "HomePage") as? HomeVC
controller?.managedObjectContext = self.managedObjectContext
self.present(controller!, animated: true, completion: nil)

Yup, that's the problem. Instead of returning to the existing HomeVC, you're making a new HomeVC and presenting that on top of yourself. So you just keep piling up the view controllers.

What you need to do to get back home is unwind what you did to get here. If present, now dismiss. If push, now pop.

Upvotes: 2

Related Questions