views:

146

answers:

2

Somewhere I was reading that I would run into memory problems when I give up a view temporary due to an low memory warning (loading it again as soon as the user wants to see it), if theViewController class does not do things like this on every outlet of that view:

-(void)dealloc {
    [myView release], myView = nil;
    [myLabel release], myLabel = nil;
    [super dealloc];
}

I am confused here, because actually I thought that [myView release] would also make the nil-thing, saying that variable holds no object anymore. Why twice? Or is there something I missed?

+5  A: 

Calling [myView release] doesn't change the value of myView, it decrements the retain count of the object that myView points to (and when the retain count of an object goes to zero, it deallocs itself). After calling [myView release], myView still contains the address of the view object, but if myView was the only owner, that object has dealloced itself and the memory is no longer valid (and my now be occupied by another object or other data). By setting myView to nil, you make sure that you don't accidently use the old memory that used to belong to myView, and you can now test if myView has been initialized or discarded.

Note that you don't need to set myView to nil in your -dealloc method, since your view controller is going away at this point anyway, but you would want to do this if you discard your view in response to a low memory warning. You might also consider discarding the whole view controller if its view isn't visible.

Don McCaughey
thanks. So in case of an low memory warning, I would write [myView release], myView = nil; right inside that low memory warning eventhandler-method? Or would self.myView = nil just work the same way?
Thanks
Assuming your @property myView is defined as retain or copy, either way would work.
Don McCaughey
A: 

When a view controller gets a memory warning, and the view is off-screen, it may set the view property to nil. But that won't release any subviews that you might be retaining in other properties. So here's how you can handle that:

- (void)setView:(UIView *)view
{
  [super setView:view];
  if (view == nil)
  {
    // Release-and-nil any subviews that you might be retaining.
  }
}
Chris Lundie