R – write [anView release], anView = nil; rather than [anView release];

cocoa-touchiphonememory-managementuikit

Somewhere I was reading that – regarding low memory warnings and giving up an non-visible view with all it's subviews (= a whole nib, I think), you should do that:

-(void)dealloc {
    [anView release], anView = nil;
    [someImageView release], someImageView = nil;

    [super dealloc];
}

rather than

-(void)dealloc {
    [anView release];
    [someImageView release];

    [super dealloc];
}

What's the reason for grounding those pointers to nil (= "no object"), after I call release? Let me guess: Some other method could have -retain'ed the view for some reason (anyone any example for when this could happen?), then the didReceiveMemoryWarning thing happens, and you release a whole nib+view that's currently not visible (i.e. in a multiview-app). As soon as the user wants to see that view again, you would quickly load the nib again and then: It loads all views, connects the outlets, and BANG! Your other retain'ed view's are hanging now without any pointer somewhere lonely in the memory brick, causing a fat and deep memory leak until your app crashes.

Right/Wrong?

Best Answer

rather than doing the expicit release and set to nil, if your accessors have properties associated with them yoc and do the following as a more concise method:

- (void) dealloc
{
    self.retainedProperty1 = nil;
    self.retainedProperty2 = nil;
    self.copiedProperty = nil;
    self.assignedProperty = nil;
}

this way you can have code that has less repetition since the synthesized code will take care of your releases for you.

Edit: i should point out that your properties can't be readonly or else you get compiler errors for obvious reasons :)

Related Topic