简体   繁体   中英

iOS UINavigationController - removing a view controller from the navigation stack does release it at all

I have been fiddling with UINavigationController for while but this problem is a little tricky for me now,

I have a UINavigationController with three view controllers.

A -> B -> C

and when I come to C view controller in the viewDidLoad() I am removing B from the stack now if I tap back on C it goes to A, everything is working as expected but B never gets released but C does.

Removal code:

    if self.navigationController != nil{
        for viewController in (self.navigationController?.viewControllers)!{
            if viewController.isKindOfClass(MyVCKind.self){
                self.navigationController?.viewControllers.removeAtIndex((self.navigationController?.viewControllers.indexOf(viewController))!)
            }
        }
    }

So I tested and profiled B view controller just to be sure that I don't have anything leaking there, everything is fine when I go from B -> A by tapping back on B, B is getting flushed out but the problem is only when I am manually removing B from the stack.

FYI I don't want to set a custom back button and override the action, I want the default behavior and with no leaks.

Any help is appreciated.

It was really weird that I have found another mysterious strong reference in making network calls in my app so that was the reason the second view controller was not getting flushed out after fixing that leak everything is working as expected. The below code just works fine.

 if self.navigationController != nil{
        for viewController in (self.navigationController?.viewControllers)!{
            if viewController.isKindOfClass(MyVCKind.self){
                self.navigationController?.viewControllers.removeAtIndex((self.navigationController?.viewControllers.indexOf(viewController))!)
            }
        }
    }

It's because (self.navigationController?.viewControllers returns non-mutable array (ie NSArray ).

So, you can't remove object from it.

So, you can manage this scenario something like,

first get array of viewcontrollers then convert it to mutable array then remove desired object or viewcontroller from it and then set that array as viewcontrollers of your navigation controller

You can refer this so post also!

Update :

Another way :

   override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {


    self.removeFromParentViewController()

   //OR

    self.navigationController?.popViewControllerAnimated(false)


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM