Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a view controller from memory when instantiating a new view controller

In my app, I am instantiating new view controllers instead of using segues because it looks better in animations as a result, my views keep running in the background. This causes large memory leaks.

My code to go back to the main screen is:

let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
        let vc  : UIViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MainScreen") as UIViewController
        self.presentViewController(vc, animated: false, completion: nil)

This view controller is still active in the background and therefore shouldn't be instantiated again. How do I do this.

When I close my view controller using the above code, it also does not unload it, it keeps running in the background. How do I make it unload as soon as the screen disappears.

I have tried doing

override func viewDidDisappear(animated: Bool) {
    super.viewDidDisappear(animated)
    view.removeFromSuperview()
    view = nil
}

However this does not work properly. How do I properly destroy a view controller from memory when exiting a view controller in this manner.

like image 222
TZE1000 Avatar asked Apr 28 '16 16:04

TZE1000


People also ask

How do I remove ViewController from memory?

You can't remove a view controller from within itself (i.e. viewDidDisappear) - what you need to do is to remove all references to it, at which point ARC will deallocate it.

How do I dismiss the current view controller?

When it comes time to dismiss a presented view controller, the preferred approach is to let the presenting view controller dismiss it. In other words, whenever possible, the same view controller that presented the view controller should also take responsibility for dismissing it.

How do I remove a view controller from storyboard?

To delete the View Controller from the storyboard, select the View Controller by clicking the Show Document Outline icon and then clicking on View Controller Scene in the Document Outline. Then press Backspace or choose Edit > Delete.


1 Answers

An important reason for this problem is related to the memory management!

if you have 'strong reference' or 'delegate' or 'closure' or other things like this, and you didn't managed these objects, your view controller has strong reference and never be closed.

you should get 'deinit' callback in view controller after than viewDidDisappear called. if 'deinit' not called so your view controller still is alive and it has strong reference.

like image 196
Saeed Avatar answered Nov 11 '22 20:11

Saeed