I want to free up memory my ViewController used after dismissing it. I use the following code to present the new ViewController and dismiss the old one:
let sB: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newVC: UIViewController = sB.instantiateViewController(withIdentifier: "MyVC")
self.present(newVC, animated: true, completion: { x in
oldVC.dismiss(animated: false, completion: { _ in //oldVC: variable keeping track of currently visible view controller
print("done")
})
})
This code successfully presents newVC
and prints done
after dismissing oldVC
. However, my memory still stays as high as it was when having oldVC
on screen.
What am I doing wrong?
presentingViewController
and presentedViewController
are nil
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.
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.
To dismiss the popover after creation, call the dismiss() method on the Popover instance. The popover can also be dismissed from within the popover's view by calling the dismiss() method on the ViewController.
Check the following issues:
Solution:
UINavigationController
and using setViewControllers
to manage the transition of your ViewControllers.oldVC
If you really do not understand. You can search:
Your oldVC
will not be deallocated, since your newVC
(and any UIViewController
) keeps by default a strong reference to its presentingViewController
- the controller that presented it. If this was not the case, you would never be able to safely dismiss your newVC
without disturbing the view hierarchy.
As far as your specific problem is concerned, in order to deallocate your old view controller, I would suggest dismissing the oldVC
first and then display your newVC
from another ViewController, earlier in the stack (could be the UIApplication shared().keyWindow?.rootViewController
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With