How can I manage the potential endless pushing of

2019-03-30 17:42发布

问题:

I have an app that is made up of a UINavigationController that pushes ViewControllers from 3 different tabs.

The trouble I am foreseeing is that current structure allows the user to endlessly add VC's onto the stack.

I have a tab called pharmaceuticals and another called pathogens. If you drill down far enough in pharmaceuticals you get to a list of the pathogens it is effective against and the user can select a pathogen to see more information about it. This causes the app to push a new pathogenVC.

Now the user can drill down to the list of pharmaceuticals the pathogen is susceptible to and select it, which cause a new VC in the pharmaceuticals tab.

and so on and so on...

each time there is an additional 1.5Mb added to the memory footprint.

How can I best manage this?

回答1:

You should focus on minimizing your memory footprint by releasing resources you can easily re-create instead of trying to stop the user from pushing 100 view controllers onto your stack. Apple doesn't do that either.

Open the 'iTunes Store' app and search for "Hugh Laurie", select the album "Let Them Talk", then on "Hugh Laurie >", then on "Let Them Talk", then on "Hugh Laurie >" and so on. You can keep going and going and going. When the user does this for a very long time, the app will probably run out of memory and crash.

If you try to load 20 tons of bricks onto your Toyota Pickup, it will probably be crushed like an empty Capri Sun packet. This is intentional destructive behavior and IMHO it is OK for the app to terminate if the user forcefully tries to overload it.

However, you can make this point almost unreachable and thus this scenario very unlikely by releasing memory in your off-screen view controllers. Implement didReceiveMemoryWarning (example: How to implement didReceiveMemoryWarning?) to release things you can easily re-create from disk or the network (images, Core Data objects etc). That way, you can bring your memory footprint way down and your users will only be able to make your app crash if they have several hours on their hands and nothing better to do than to push view controllers. Which would be sad.



回答2:

You can implement your own UINavigationController subclass. You'll need to implement at least pushViewController:animated: and popViewControllerAnimated:. During a push, you'd discard one of the view controllers (thereby releasing the memory), and in pop, you'd create it again, using the data that you keep around. Basically, you'll switch from keeping the entire stack of view controllers to having just a couple elements, with the logic to restore the ones further down the stack.

This is a simplified description. In the actual app, you'll want to keep at least the previous view controller around, so that your back button and the swipe-from-the-edge back gesture work smoothly.