How to remove a subview (or all subviews of a view

2019-04-15 22:28发布

问题:

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;

回答1:

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 to retain that's all you'll need.



回答2:

Another solution: don't remove your UIButtons but re-use them. Don't know the exact use-case for you, but you may assign tags to your UIButtons and find them with [UIView viewWithTag:].

UIButton* btn = [[UIButton alloc] initWithFrame:frame];
btn.tag = 42; // some unique identifier for the button.. dont use 0 (zero)
[tabsView addSubview:btn];
[btn release];

later...

UIButton* btn = (UIButton*)[tabsView viewWithTag:42];
if(btn && [btn isKindOfClass:[UIButton class]]) {
    // do some stuff with btn
}

Besides: In my opinion you only should use autorelease when you've no other options. Here it's easy for you to release btn after adding it as subview.