Memory problems when pushing many view controllers

2019-03-31 19:35发布

I'm making an interactive book for the iPad and am using UINavigationController to implement the navigation between a page and the next. When a user turns the page, the next page is pushed on top of the navigation stack.

I'm now 15 pages into the app, and the app crashes when I try to go from page 14 to page 15. No error message in the console, nothing in the device's crash logs neither.

Each view controller's scene in the storyboard has UIImageViews displaying images that are between 5MB and 20MB. The view controllers' viewDidLoad method is called just once. The total size of all the app's assets is below 200B. I'm using ARC.

I've ran the app using Instruments' Memory Monitor. The app's Real Memory consumption increases by about 80MB every time a new page is turned, and crashes when it reaches 800MB (the device is an iPad 3).

  • Why such an enormous memory consumption? Is this because the UIImageView in the Storyboard's scenes cache the images?

  • What would be the best way to free up memory when you use a UINavigationController and ARC?

I tried adding setting all the view controller's subviews to nil in the view controllers' viewDidDisappear: method, but memory consumption stayed the same.

2条回答
在下西门庆
2楼-- · 2019-03-31 19:36

When you use a UINavigationController, each ViewController you push stays in memory forever (well, until your app exits) unless your user presses the back button on that particular ViewController. It keeps a stack of ViewControllers - with the visible one at the top.

So the simple answer is don't use a UINavigationController for this. I'd suggest building your own ViewController that 'knows' which is the next and previous pages and manually loads and removes them as and when required. This way you can ensure that you only have one page in memory at once (except for during the transitions - maybe you could use this animation for the transitions http://cocoacontrols.com/platforms/ios/controls/xbpagecurl).

查看更多
Fickle 薄情
3楼-- · 2019-03-31 19:54

You probably don't want to use a UINavigationController for this purpose. You really want one view controller to manage all your pages and render the new page on the same view while removing the old.

查看更多
登录 后发表回答