Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load a view controller and then remove the previous one from memory

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

like image 315
agro1986 Avatar asked Apr 14 '16 10:04

agro1986


People also ask

How do I go back to the previous view controller in Objective C?

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];

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.

How do I present a view controller from another view controller?

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.


1 Answers

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.

like image 111
Zell B. Avatar answered Oct 17 '22 04:10

Zell B.