4
votes

I am new to iOS and wondering how to properly implement view controller unloading/reloading.

Right now my app has a NavigationController with a MainMenuViewController (custom view controller) set up as root view controller. During the course of app lifetime, new ViewControllers are pushed/popped on the Navigation Controller. This works fine, the appropriate ViewControllers are initiated (from NIBs) the first time they are pushed to the stack.

However, I now want to unload one particular ViewController when it is popped, then reload it automatically when it is pushed again.

I have added a [self release] to that ViewControllers viewDidDisappear: and it unloads, but when i try to push the view again, i get a message sent to dealloc'ed instance error and crash. Therefore, my questions are:

  1. Is that a proper way to unload a popped ViewController?
  2. How to check if a given ViewController is loaded or not?
  3. How to force a reload? With loadWithNib:, then push onto navigation stack?

Regards,

Peter

1

1 Answers

3
votes

Welcome to iOS programming. Your crash is a memory management issue. It may take you a bit to get the hang of it but memory management gets way easier if you just follow one rule:

an object needs to release anything it retains (alloc is equivalent to retain)

In this case, your view controller is releasing itself and it definitely did not retain itself. Here's how the sequence works with a navigation controller:

  1. The navigation controller is initialized with a root view controller (the first one on its stack). Lets call this firstViewController

  2. A user action tells firstViewController to initialize secondViewController and push it onto the navigation controller. In most cases, firstViewController will release the instance of secondViewController after pushing it. At this point, firstVC is done with secondVC. The navigation controller is now retaining secondVC

  3. User touches the back button on the navigation bar of secondVC. The navigation controller will pop secondVC from the stack and release it. As long as no other object is retaining it, secondVC will get be dealloc'ed.

  4. Now user is back in firstVC. They can do the same user action which will init and push a new instance of secondVC.

Hope that helps a bit.

I'd also recommend you (re)read the Apple docs and look at the sample code referenced in the framework docs.

http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/Introduction/Introduction.html