开发者

iOS SDK - dealloc implementation - Release child views first?

I am finishing up an iPad application, and for me, that means filling in all of the dealloc methods in my classes.

I have many views in my开发者_StackOverflow社区 nib and most of them contain subviews (i.e. UIViews, UILabels, etc.). Should I release the child views before releasing the parent? If the parent view is released, will its child views be released, as well?

Sample:

-(void)dealloc
{
    [super dealloc];
    [childView release];  // Do I need this if I use the next line?
    [parentView release];  // Will this perform the line above?
}

Both childView and parentView are properties of my view controller. Both have been retained.


Anything that you have retained (whether explicitly or through a retained property) needs to be released for the memory management to be balanced.

Also, you should invoke [super dealloc] at the end of your dealloc implementation, not the beginning (for instance, because you might depend on superclass resources still being available at the time).


By the way, saving your dealloc-writing until you're finishing up work on the app is a backwards way to go. I know it seems like house-cleaning work, but the fact is until you're managing memory properly, you're going to have a very skewed view of how your app really performs.

Ideally you should write your dealloc calls as you write your @synthesize statements. In other words, you add a property to your class, you set it up as a retained property, you write its @synthesize and -release code. That way you know your memory management is basically clean (I mean, at the class property level anyway) and you can code with confidence.


Since you specified that you have subviews from a NIB, it sounds like you also may need to pay close attention to the viewDidUnload method.

Any views which are automatically allocated from the nib you can implicitly release by setting the outlet to nil. For example:

- (void)viewDidUnload {
    [super viewDidUnload];
    self.subviewOutletOne = nil;
    self.subviewOutletTwo = nil;
}

Then for any objects which you explicitly retain, you release them in the dealloc method like you are planning to do:

- (void)dealloc {
    [myDataArray release];
    [coolAnimatedImage release];
    [myCustomSubview release];
    [super dealloc];
}

Also be sure to check out the LEAKS instrument. This is a random tutorial for using the built in leak analysis tool. There may be others / better ones. It can a pain to get up and running the first time but is completely worth it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜