i was reading this code, where setRegions is called after RootViewController is released : i find it a bit strange : does it mean RootViewController is still accessible, even if it was released and self.navigationController “owns” it ?
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Create the navigation and view controllers
RootViewController *rootViewController = [[RootViewController alloc] initWithStyle:UITableViewStylePlain];
UINavigationController *aNavigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
self.navigationController = aNavigationController;
[aNavigationController release];
[rootViewController release];
[rootViewController setRegions:[Region knownRegions]];
// Configure and display the window
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
}
Thanks
This is bad code.
An object should retain another object for as long as it cares about it. And in this case that rule is broken. The
rootViewControlleris released, and then as you note, a method is called on it. This can be dangerous.In this case, it works. This is because
rootViewControlleris passed to another object, which retains it. So when we release it, it still has a positive retain count and is not deallocated. So our reference to it still works, and methods called on it work fine.But lets say some implementation changed and
initWithRootViewController:now no longer retained it’s argument for some reason (an assumption you can’t really make all the time). Suddenly this all crashes becauserootViewControllergets deallocated.To fix this funk, you just need to move
[rootViewController release];to after the last useful reference of that object in this function. Your code then becomes more robust and more correct.Last thing to note:
releaseanddeallocare very different things.releasedoes not necessarily destroy objects. It simply decrements theretaincount by one. And if thatretaincount ever gets to zero, only then is the object is deallocated. So this code works because areleasehappens but without triggering adealloc.