Objective-c – How to remove a subview (or all subviews of a view)

cocoa-touchiphoneobjective cuiview

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;

Best Answer

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.

Related Topic