Releasing ViewControllers form memory inside a UIN

2019-09-03 12:29发布

问题:

I'm building an app using a UINavigationController. I have a ViewController that shows some content, and when it receives interaction from the user (tapping a button for example) a new ViewController is displayed.

Here is the code:

FirstViewController.m

-(IBAction)goToSecondVC:(id)sender{  
    SecondViewController *secondVC = [[SecondViewController alloc] init];
    [self.navigationController pushViewController: secondVC];    
}

I want to release FirstViewController from memory once SecondViewController has appeared. And then for example, if I jump from SecondViewController to FifthViewController I'd like SecondViewController to be released as well. The memory consumed by the app increases when I jump back and forth between controllers, meaning that they are not being released. Any thoughts?

This is what happens with the memory indicator when I switch between controllers. ARC is activated:

回答1:

UINavigationController uses stack data structure to mange viewControllers, so you have 2 operations: Pop and Push. firstVC --push-> secondVC --push-> thirdVC. now first, second and third will stay in memory for faster popping. If you think that this consume a lot of memory than you can use other presentations for your viewController, for example modally presenting it, or adding it as a chiled viewController and then remove it manually, but with UINavigationController, only pop operation will ensure that the viewController will be released (if no other strong references on it).



回答2:

No. You don't want to release these view controllers. They're part of the navigation stack and remain in memory so they can quickly be navigated back to. If your app is using too much memory, you need to find other places to consume less memory or you need to use something other than a navigation controller.



回答3:

The previous answer is correct, you should avoid such logic.

But there is a trick to do such stuff. You can -setViewControllers on your navigationController and paste there only those vc you want to stay in stack.

For ex. to release FirstViewController, you can call on Second (on viewDidAppear for ex.)

NSArray *viewControllers = @[self];
self.navigationController.viewControllers = viewControllers;


回答4:

You cann't do this. Because Navigation controller hold all view controller when it is push from it. When you try to pop, it will release it. Before you try to manually release it. It will get crash. If upnormally increase memory during navigation means, use instrument and find out leaks and fix it.