Take the 2-minute tour ×

In a view based app, I display a view and once the user is finished with that view, Done is clicked and the view is removed. However, that does not dealloc the view, which is what I want to do. What is the proper way to dealloc this type of view?

Currently, I'm nil'ing out the second view before it is called. That seems to work and the second view is reinitialized. However, isn't it more appropriate for the second view to destroy itself (nil itself after removeFromSuperview)?

In first view:

//show next view
aView = nil;
if(aView == nil)
  aView = [[AView alloc] initWithNibName:@"aView" bundle:nil];
[self.view addSubview: aView.view];

Click Done in aView

[self.view removeFromSuperview];
share|improve this question

4 Answers 4

up vote 1 down vote accepted

The method removeFromSuperview will automatically release "aView.view", so you shouldn't release aView in the first view controller. I think you've declared AView *aView in head file, but you don't need to. You may declare the aView as a local variable like this:

// go to second view
SecViewController *sec = [[SecViewController alloc] initWithNibName:@"SecView" bundle:nil];
[self.view addSubview:sec.view];

// go back
[self.view removeFromSuperview];
share|improve this answer
Thanks. I removed the header file declaration and it works fine. –  4thSpace Dec 30 '09 at 17:24

If you previously set your viewController to first responder status (like to respond to motion events) the responder chain will retain the controller. You must resign the first responder to destroy the controller completely.

[self resignFirstResponder];
[self.view removeFromSuperview];
share|improve this answer

both of the above answers are correct theory for how you should memory manage in objective c.

as per the dev documentation:


callling removeFromSuperview will actually call release FOR you, so you are okay, I think.

share|improve this answer
No - it doesn't release for you. dealloc of the child view is never called. Rather than view, I should say viewcontroller. –  4thSpace Jan 1 '10 at 5:51

Immediately after

[self.view addSubview: aView.view];

You should add:

[aView release];

Your subview has been retained by your view controller's view so can be release.

share|improve this answer
That doesn't work. I have an IBAction connection to a button in aView. When I click it, I immediately get EXC_BAD_ACCESS. Breakpoints in the button are never hit. –  4thSpace Dec 30 '09 at 0:10

Your Answer


