简体   繁体   中英

Does moving a view to new superview automatically release it from old superview?

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?

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.

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM