views:

773

answers:

3

It's not clear, to me anyway, if a UIView is automatically released from its superview if you use addSubview to add it to another view?!? I know a view can only have ONE superview but I'm not clear about how, exactly, to go about moving a subview from one superview to another.

retain view, release (from old superview), addSubview to new superview

or

simply addSubview to new superview?

+2  A: 

Adding a view to a superview retains that view, removing the view from a superview releases it.

[subview retain]; // because next line will release
[subview removeFromSuperView]; // released by superview
[otherSupView addSubview:subview]; // retained by new superview
[subview release]; // because you retained it in line 1
EightyEight
OK, do you know what would happen if you just re-assign (add) the view to a new superview without the retain, remove, release?
Meltemi
Probably nothing. Maybe some weird stuff if both superviews are visible at the same time.
EightyEight
+1  A: 

To be safe, put a retain on the view before you move it like so:

[[theView retain] autorelease];
[theView removeFromSuperview];
[newSuperview addSubview:theView];

If the superview is the only object that has a retain on the subview, then the subview will be deallocated when it is removed from the superview. The retain and autorelease guarantees that the view won't be deallocated while you're using it in the function (because there is an extra retain on it).

Tom Dalling
+2  A: 

To the question of whether the view is released when -removeFromSuperView is called, it is, and this is documented in the UIView reference under -removeFromSuperView. It is not as explicitly stated that -addSubView: calls -removeFromSuperView, but it is implied and can be tested by overloading -removeFromSuperView in a UIView subclass.

Therefore I can think of no reason to call -removeFromSuperView in this case. There's no memory-management reason to do it, so this is adding some code complexity (and therefore potential errors) for little value. Even in cases where I wanted to emphasize to later developers that this view is changing view hierarchy, I would use a comment rather than the extra retain/release here.

Rob Napier
“… it is implied …” Where? I couldn't find it in the documentation for `-[UIView addSubview:]`.
Peter Hosey
The iPhone App Programming Guide's discussion of the view hierarchy ("Adding and Removing Subviews") indicates that it is memory managed like a collection, and indicates that a view can only be in one hierarchy. It would thus be incorrect for it not to be removed from one before being put into another, so either Cocoa would do this or Cocoa would throw an exception if you failed to (such as when you insert nil into an NSArray). Furthermore, "willRemoveSubview:" is listed among the methods called when you add a subview to a parent view.
Rob Napier