After reading:
Memory management of a view controller in Objective-c
and
Does UIView's addSubview really retain the view?
I wrote the following code to toggle a subview:
@synthesize switchableView, viewSelector, currentSubview;
//...
if(switchableView.subviews.count != 0)
[[switchableView.subviews objectAtIndex:0] removeFromSuperview]]
self.currentSubview = (veiwSelector.selectedSegmentIndex == 0) ?
[ViewA new] : [ViewB new];
[switchableView addSubview:currentSubview.view];
//[currentSubview release]; //<---crashes if I uncomment this line
It seems to run fine if I comment out that release line, but I can’t wrap my head around why. Here’s the way I understand what happens and maybe someone can tell me where I go wrong:
So lets consider currentView:
-
A gets alloc-ed by the ‘new’ message–retain count=A:1
-
A gets retained by the setter–retain count=A:2
-
A’s view gets (supposedly) retained–retain count=A:2.1
next time through…
-
A’s subview gets released count=A:2
-
B gets alloc-ed by the ‘new’ message–retain count=B:1, A:2
-
A gets autoreleased by the setter– B:1, A:1
-
B gets retained by the setter–B:1, A:1
-
nothing ever gets rid of A?
So should I change my code, or am I wrong about the way memory management works in this language…or both?-
Your understanding of retain and release is correct, as is your code. That suggests that the problem lies outside of the code you’ve posted. For example, you would have this problem if your currentSubView property was defined as
assigninstead ofretain.You code is not structured well, however. This would be much clearer:
Furthermore, view controllers are meant to be cached, not created and released each time the user toggles a display. Typically, you create your view controllers beforehand, and access their
.viewproperty when necessary to display the view.UIViewControllerwill automatically deallocate non-visible views in low memory conditions, and re-allocate their view when the.viewproperty is accessed.