0

I have a UIScrollView declared as an iVar in the implementation file of a class that uses ARC:

@interface RecipeBrowserViewController ()
{
    UIScrollView *tempScrollView;
}

This is necessary because during execution I need to sometimes add the UIScrollView to my view, and other times remove that same UIScrollView:

if (someTest) 
{
    tempScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    tempScrollView.delegate = self;
    [self.view addSubview: tempScrollView];
}
else 
{       
    [tempScrollView removeFromSuperview];
}

My expectation was that the tempScrollView would be deallocated once it's removed from the superview, but this is not the case. Presumably, because the iVar is still referencing it?

Adding tempScrollView = nil after removing it from the superview clears this up, but I'm not sure what the correct approach is. Am I supposed to declare a weak iVar instead? Thus far I have only seen weak suggested for delegates or other two-way iVars that would otherwise lead to a strong reference cycle. Is this another place I should be using it?

4

1 に答える 1

1

Adding/removing the scroll view is a separate issue from ivar memory management. What you've got is correct, except that you should indeed set the ivar to nil when you're done with tempScrollView.

When you add View B (the scroll view) as a subview of View A (self.view), View A keeps a strong reference to (i.e. retains) View B. When you remove View B as a subview, View A removes its strong reference to (i.e. releases) View B. However, the ivar tempScrollView is strong, so the view controller (self) maintains a strong reference to the scrollview, and as you've seen, it's not deallocated. The way to remove that strong reference is to set the ivar to nil.

I'd add that in my opinion, you should use an @property for tempScrollView instead of using an ivar directly. With ARC it's not as much of an issue, but in general it's better to encapsulate memory management inside of property accessors, and it's the same number of lines of code at this point.

于 2012-09-29T18:37:05.680 に答える