Take the 2-minute tour ×

I have a UIView subclass called ToolbarView that sort of acts like a floating window and has a UIToolbar that has an "X" button that can make the window disappear. My question is, is it possible for the object to delete itself from within its own class?

For instance, within ToolbarView.m, I have a method closeButtonPushed which fires when the X button is pushed. Is it as simple as to remove the view from its superview, and then call dealloc? Is it even necessary to call dealloc as once it is removed from the superview there won't be any other pointers to it. Or is this bad memory practice?

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

Yeah, don't call dealloc ever. If the superview is the only object that has a reference to your view, removing the view will cause its retain count to go to 0, and the runtime will then deallocate the object for you.

share|improve this answer
Don't you have to nil it though, after the removeFromSuperView? –  Rick van der Linde May 26 '12 at 5:46
Probably a best practice to ensure you don't access bad memory after the object is deleted, but not necessary. It will not affect the memory management at all –  darren May 26 '12 at 6:58
Ok, did not know that, thanks :) –  Rick van der Linde May 26 '12 at 19:32
add comment

What you have to do is in closeButtonPushed method is, call

 [self removeFromSuperView];

it will remove the ToolbarView object and IOS will call the dealloc method and release objects. No need to call dealloc manually.

share|improve this answer
add comment

Your Answer


