views:

63

answers:

2

I wonder if someone can help me out with regards to the memory management in the code below. I am particularly interested in rootController, does it get retained when I do initWithRootViewController or does it instead (which is my guess) get retained with window addSubView: I am just curious what is happening ...

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    Base_TableViewController *rootController = [[Base_TableViewController alloc] init];
    navController = [[UINavigationController alloc] initWithRootViewController:rootController];
    [window addSubview:[navController view]];
    [window makeKeyAndVisible];

    [rootController release];
    return YES;
}

- (void)dealloc {
    [navController release];
    [window release];
    [super dealloc];
}

EDIT:

So essentially the code above is correct, the release at the bottom cancels out the alloc at the top, "rootController" is retained by navController?

Many thanks, much appreciated.

Gary

+1  A: 

After the call to alloc init, the retain count on rootController will be one. If navController does a retain in it's initWithRootViewController message, then after that line, it will have a retain count of two (I am pretty sure UINavigationController will retain it's root view controller).

Adding the navController's view to the window will not affect the rootController's retain count (It will increment the retain count on the UIView member of navController).

After the rootController release, it will decrement the retain count down to one.

Edit

Yep. In fact you could simplify the code a little more by removing the release at the bottom and sticking an autorelease around the initial allocation.

Cannonade
Are you sure window wouldn't retain it? UIView retains its subviews and UIWindow is a subclass of UIView, so it should too.
Toastor
Yep. The addSubview will just increment the retain count on the view member of the navController. It won't affect the retain count on the view controller.
Cannonade
You're right. How do you say in english when you're reading something but your mind remembers something else? :)I didn't see that he was calling the controller to return its view. My bad!
Toastor
@Toastor No prob :P It is easy to miss a detail like that when you are reading the question.
Cannonade
+1  A: 

initWithRootViewController: retains navController. And addSubview: retains navController.view

EDIT: Yes, that is true. And [rootController release] does not actually release rootController, it just decrements its retain count by one since it is already retained by initWithRootViewController.

ardalahmet