Iphone – Releasing subviews

iphone

I have a UIScrollView that has multiple pages of information that are added as subviews to the scrollView. Each subView's controller is stored in a NSMutableArray in the scrollViewController.

I have some memory leaks in the subviews, and I am trying to fix them by making sure that each subview controller's dealloc method is called. I'm doing that by releasing the view controllers from within the scrollView controller's dealloc method.

When I try to release the array after the subViews controllers are released, the application crashes.

Code follows… what am I doing wrong?

- (void)dealloc {

// Loop through the array of subView controllers and release them
for ( int i = 0; i < [viewControllers count]; i ++ ) {
    [[viewControllers objectAtIndex:i] release];
}

[viewControllers release];  // Crashes here unless I remove the loop above
[scrollView release];
[pageControl release];
[theKnot release];
[super dealloc];

}

Best Answer

NSMutableArray takes ownership of objects it contains -- it increments their reference counts when added, and will release its objects when it deallocates itself.

Assuming you released or autoreleased each view controller after you put it in your viewControllers array, there's no need loop over objects in viewControllers and release them -- the array will do it for you.

You're crashing when releasing the array because the array is trying to release objects that you already released and are now invalid.

Related Topic