Memory Management question


#1

Hello,

This code from page 132

	HeavyViewController *hvc = [[HeavyViewController alloc] init];
	[window addSubview:[hvc view]];

shows up in the static analyzer as a potential memory leak.
But the application auto rotates the view as expected.

If I change the code to release hvc.

	HeavyViewController *hvc = [[HeavyViewController alloc] init];
	[window addSubview:[hvc view]];
	[hvc release];

Then the application no longer auto rotates when the device orientation changes.

Should I be ignoring the static analyzer in this case?


#2

Yes, the static analyzer is “wrong.”

You create the view controller and it creates its view, then that view is added to the window. Therefore, the view controller’s retain count is 1 and the view’s retain count is 2. You release the view controller, it then gets destroyed. The view’s retain count is 1 and the view controller doesn’t exist.

You need that view controller the entire time the application is running, so you shouldn’t release it. This is less confusing in iOS 4.0 where you had over the entire view controller to the window with setRootViewController:. But, the rule here is: don’t release objects if you still need them.


#3

Thanks for the quick response Joe. do you ever have any down time?

I dug into the UIView class reference and finally realized that

was only increasing the retain count on the view of hvc. So when I released hvc the view was still retained by the window but no longer had a view controller.

Thanks again.


#4

[quote=“devans”] do you ever have any down time?
[/quote]

Sounds boring! :slight_smile: