Let's say I have a view controller A (subclass of UIViewController) which has a button, and if you press the button it will load and display view controller B (subclass of UIViewController) using a segue (so I made the connection using interface builder). Segue type is Show.
When B is displayed, I will never ever go back to A, so I want to kill, destroy, crush, maim it, so that the precious few bytes of memory can be used for other things.
Here is the code for A:
class ViewControllerA: UIViewController {
deinit {
print("I am immortal haha I cannot die!!!")
print("This will not be displayed!!!")
}
}
Here is the code for B:
class ViewControllerB: UIViewController {
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
print("Go away old view controller!!!")
appDelegate.window!.rootViewController = self // (1)
}
}
My code at (1) replaced the root view controller of the app. However, the old view controller seems to linger in memory, because the print message of its deinit is not displayed.
How can I accomplish the simple task of unloading an unneeded view controller and its view? Thanks a lot
To go one view back, use below code. This will ensure that the smooth transition between views are retained. UINavigationController *navigationController = self. navigationController; [navigationController popViewControllerAnimated:NO]; [navigationController popViewControllerAnimated:YES];
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.
Using segues in your storyboard is the recommended way to present and dismiss view controllers. A segue is a visual representation of a transition from one view controller to another. A segue starts with an action such as a button tap or table-row selection in the initial view controller.
When you present ViewControllerB
from ViewControllerA
, ViewControllerB
hold a strong reference of ViewControllerA
in its presentingViewController
variable so thats why ViewControllerA
never get deinitialized. What you need to do is to change app delegates window rootViewController
directly from ViewControllerA
which means you must get rid of segues.
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