Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UINavigationController: When Does a Pushed View Receive the Dealloc Message?

I would expect that after I push a view controller I then need to release my ownership of the view controller like I did below.

CustomViewController *nextViewController = [[CustomViewController alloc] initWithNibName:@"CustomView" bundle:nil];
[[self navigationController] pushViewController:nextViewController animated:YES];
[nextViewController release];

After I do that, I assume that the navigation controller has ownership of that object and will release it when done which would then call dealloc on my customViewController. I would expect that to happen when I tap the back button on the navigation bar and the view is no longer displayed. That does not happen though. I added an NSLog(@"CustomViewController did receive dealloc") into the dealloc method of CustomViewController but it never gets printed. Is this normal behavior?

Is the navigation controller just doing something like keeping that object in case it needs it at some point? Will it get rid of it when memory starts to run out? I tried simulating a low memory warning but nothing happens. I have a feeling the answer to this question will be that I should just not worry so much and follow the standard procedure for retain/release/autorelease. That said though, has any one else delved into this a little bit further and found out an absolute answer?

like image 580
startoftext Avatar asked Feb 05 '10 20:02

startoftext


1 Answers

"Is the navigation controller just doing something like keeping that object in case it needs it at some point?"

Yup. That is exactly what it is doing. It will send you viewDidLoad and viewDidUnload messages though. And that is the place where you should allocate and free resources that your viewcontroller uses.

Note that viewDidUnload will only be called when the system thinks it needs to free memory.

If you need more immediate control over when things are loaded and freed then a better place might be viewWillAppear: and viewDidDisappear:.

My alloc/init methods for viewcontrollers are usually pretty empty or not even there.

like image 166
Stefan Arentz Avatar answered Sep 20 '22 05:09

Stefan Arentz