Search code examples
memoryxcode4uiviewcontrolleruiimageviewxcode-instruments

App is taking too much memory until a crash ! (iPhone)


I am quite beginner in development and I'm making an application that have about 150 ViewControllers ! Each one have a UIImageView.

I've been doing a bit of testing, and after a use the app for a while on the iPhone itself, it Crashes when I keep viewing the ViewControllers.

I've been analyzing this in instruments, and I have no leaks, however my memory allocation just goes up and up and when I keep viewing the ViewControllers on my iPhone the usage just goes up and up until a crash.

I think it's clear that it's crashing because the app is simply taking up too much memory.

So could any one explain how to release viewControllers in order to free up the memory so there will be no crash

Thanks in advance !


Solution

  • The first question you need to ask yourself is why do you need 150 ViewControllers. Do you want to present 150 different images? If so, then multiple ViewControllers is not the way to go. You probably need to use a UIScrollView that will contain your images (not all of them at once, of course. Use lazy loading).

    What's probably happening in your case is that you call "pushViewController" each time you need to display a new ViewController, but this doesn't release the previous ViewController. It simply stacks all of the previous ViewControllers and retains their pointers.

    You see, the way Navigation Controllers work is that they have an array of view controllers. Every time you present a new view controller, it is added at the end of the array. When you click on "Back" or call "popViewController" the last item of the array is removed (and then released automatically from memory).

    See this and this questions to learn how to create a UIScrollView to scroll images.