如何删除子视图(或视图的所有子视图)
我有一个方法,在其中分配并初始化一个
UIView (`tabsClippedView = [[[UIView alloc] initWithFrame:tabsClippedFrame] autorelease];`).
此视图,其中添加了另一个视图
(`tabsView = [[[UIView alloc] initWithFrame:tabsFrame] autorelease];`).
然后我启动几个按钮
(e.g. `UIButton* btn = [[[UIButton alloc] initWithFrame:frame] autorelease];`)
并将它们添加到视图的子视图中。
现在,我有时需要删除所有按钮并重新分配它们。删除整个视图或仅删除我添加按钮的子视图是最好的方法吗?
我需要如何做到这一点(没有内存泄漏等)? 一个简单的
self.tabsView = nil;
足以删除视图及其所有子视图(即按钮)吗?
或者最好也删除超级视图,完全从头开始:
self.tabsClippedView = nil;
I have a method in which I alloc and init an
UIView (`tabsClippedView = [[[UIView alloc] initWithFrame:tabsClippedFrame] autorelease];`).
This view has another view added to it
(`tabsView = [[[UIView alloc] initWithFrame:tabsFrame] autorelease];`).
Then I initiate a couple of buttons
(e.g. `UIButton* btn = [[[UIButton alloc] initWithFrame:frame] autorelease];`)
and add them to the subview of the view.
Now from time to time, I need to delete all the buttons and assign them again. Is the best way to delete the entire view or simply the subview to which I added the buttons?
How would I need to do this (without memory leaking etc.)? Would a simple
self.tabsView = nil;
suffice to delete the view and all of its subviews (i.e. the buttons)?
Or would it better to delete the superview as well, to start entirely from scratch:
self.tabsClippedView = nil;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您的 UIView 是自动释放的,因此您只需将其从超级视图中删除即可。为此,有
removeFromSuperview
方法。因此,您只需调用
[self.tabsView removeFromSuperview]
即可。只要您的属性声明设置为retain
,这就是您所需要的。Since your UIView is autoreleased, you just need to remove it from the superview. For which there is the
removeFromSuperview
method.So, you'd just want to call
[self.tabsView removeFromSuperview]
. As long as your property declaration is set toretain
that's all you'll need.另一个解决方案:不要删除
UIButtons
而是重新使用它们。不知道您的确切用例,但您可以将tags
分配给您的UIButtons
并使用[UIView viewWithTag:]
找到它们。稍后...
此外:在我看来,只有在没有其他选择时才应该使用
autorelease
。在这里,您可以轻松地将btn
添加为子视图后释放它。Another solution: don't remove your
UIButtons
but re-use them. Don't know the exact use-case for you, but you may assigntags
to yourUIButtons
and find them with[UIView viewWithTag:]
.later...
Besides: In my opinion you only should use
autorelease
when you've no other options. Here it's easy for you to releasebtn
after adding it as subview.