Proper way of unloading/reloading a View Controller
I am new to iOS and wondering how to properly implement view controller unloading/reloading.
Right now my app has a NavigationController w开发者_Python百科ith 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:
- Is that a proper way to unload a popped ViewController?
- How to check if a given ViewController is loaded or not?
- How to force a reload? With
loadWithNib:
, then push onto navigation stack?
Regards,
Peter
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:
The navigation controller is initialized with a root view controller (the first one on its stack). Lets call this
firstViewController
A user action tells
firstViewController
to initializesecondViewController
and push it onto the navigation controller. In most cases,firstViewController
will release the instance ofsecondViewController
after pushing it. At this point,firstVC
is done withsecondVC
. The navigation controller is now retainingsecondVC
User touches the back button on the navigation bar of
secondVC
. The navigation controller will popsecondVC
from the stack and release it. As long as no other object is retaining it,secondVC
will get be dealloc'ed.Now user is back in
firstVC
. They can do the same user action which will init and push a new instance ofsecondVC
.
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
精彩评论