0
votes

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];

}

2

2 Answers

4
votes

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.

1
votes

NSArray releases its contents when it's dealloced, so the objects are being released both in your loop — which is presumably deallocing them — and afterward by the array.

You should read Apple's memory management guide if you plan to create iPhone apps. It's not that hard, but it is something you have to learn. Otherwise you'll get leaks and crashes and have no idea why. Once you understand Cocoa's few simple rules, everything will be clear.