views:

88

answers:

4

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];
+1  A: 

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.

Meltemi
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
A: 

Also:

  aView = [[[AView alloc] initWithNibName:@"aView" bundle:nil] autorelease];

You wouldn't need the 'release' message in this case.

Hector Z
This gives the same results as doing the release when I click a button (mentioned in comment below).
4thSpace
A: 

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

as per the dev documentation:

http://developer.apple.com/iPhone/library/documentation/UIKit/Reference/UIView%5FClass/UIView/UIView.html#//apple%5Fref/occ/instm/UIView/removeFromSuperview

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

Oren Mazor
No - it doesn't release for you. dealloc of the child view is never called. Rather than view, I should say viewcontroller.
4thSpace
+1  A: 

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];
iPhoney
Thanks. I removed the header file declaration and it works fine.
4thSpace