Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the root view controller is not deallocating the previous view controllers on the same window

Tags:

xcode

ios

swift

My app launches with an initial view controller (lets call it as StartVC). Now when user presses a continue button, I am presenting a navigation stack (lets call it as RegisterVC) on top of StartVC. This navigation stack will contain 5 view controllers which I am pushing on it whenever user moves forward with button actions. After the 5th view controller, I am starting a new navigation stack (lets call it as LoginVC).

Now my use case is I dont want the StartVC & RegisterVC to reside in the memory as they are of no use once user has completed his registration. In order to achieve this, I am changing the AppDelegate window's root view controller to LoginVC

Below are the options which I tried on the 5th view controller of RegisterVC:

1) Changing the keywindow

    UIApplication.shared.keyWindow?.rootViewController = LoginVC
    UIApplication.shared.keyWindow?.makeKeyAndVisible()

2) Changing the window

   let appDelegate = UIApplication.shared.delegate as! AppDelegate
   appDelegate.window?.rootViewController = LoginVC
   appDelegate.window?.makeKeyAndVisible()

3) Making the previous root view controller as nil before assigning a new one.

   let appDelegate = UIApplication.shared.delegate as! AppDelegate
   appDelegate.window?.rootViewController = nil
   appDelegate.window?.rootViewController = LoginVC
   appDelegate.window?.makeKeyAndVisible()

4) I also tried the above options directly from the AppDelegate instead of doing it from the 5th view controller.

With all the above options, I tried debugging by looking at deinit on all view controllers, but none of them got deallocated. Also, I can see that 5th view controller under LoginVC in the xcode Debug View Hierarchy.

Because of not removing them from memory, the actual problem which I am facing is after presenting the LoginVC, I have a view controller whose background color alpha is less. Because of this I am seeing the RegisterVC 5th view controller underneath it.

Any help on this appreciated...

like image 514
Naveen Avatar asked Jul 16 '17 15:07

Naveen


1 Answers

I think the rootViewController setting is not the problem. Perhaps you have a retain cycle in your other view controllers that stops them from being deallocated.

There are many ways you could accidentally do this (capturing strong references to self in blocks, not marking delegates or other back references as weak, etc).

You might be able to figure it out with Instruments. Here's a tutorial: http://samwize.com/2016/05/30/finding-retain-cycle-with-instruments/

like image 184
Lou Franco Avatar answered Sep 19 '22 22:09

Lou Franco