开发者

Object release in Objective-C: Why release an object twice in viewDidUnload and dealloc method?

I have a question about object release in objective-c. I saw some sample codes in Chapter 9 of "Beginning iphone 4 Development"(Page 287). The sample code release an object twice: both in viewDidUnload and dealloc method. Here are the sample codes:

- (void)viewDidUnload {
self.list = nil;
[childController release], childController = n开发者_高级运维il;}

- (void)dealloc {
[list release];
[childController release];
[super dealloc];}

childController is declared as an instance of UIViewController subclass. Why is it released in both viewDidUnload and dealloc method? Since childController is already released in viewDidUnload, is it necessary to release it again in dealloc method? Based my understanding I will write the code like:

- (void)viewDidUnload {
self.list = nil;
childController = nil;}
- (void)dealloc {
[list release];
[childController release];
[super dealloc];}

Thanks,

Sam


The problem is viewDidUnload is not guaranteed to be called every time like dealloc method. (check this question).

The reason to release objects in viewDidUnload is to avoid memory leaks. Since viewDidUnload is called when there's a low memory warning, you do want to clean up to avoid troubles in that case.

And also calling release on nil will not cause any problem, so it is safe to call release on retained objects in your dealloc method assuming the pointers are set to nil after been released elsewhere (like in viewDidUnload in your example).


In order to optimize available memory, is a good practice to implement lazy getters (actually lazy initializers) in UIViewControllers and release easily reallocable objects in viewDidUnload. A (simplified) lazy getter is something like:

- (UIView *)footerView {
    if (_footerView) {
        return _footerView;
    }
    UIView *view = [[UIView alloc] initWithFrame:A_FRAME];
    return (_footerView = view);
}

so, in the viewDidUnload I will release _footerView, because I can retrieve it later without effort. The release of _footerView in dealloc method, is not an error, because: 1) in objective c is ok to send messages to nil objects, 2) dealloc won't be executed at the same time as viewDidUnload but later


I've investigated a little bit because I was not sure. And all you need to know is here: When should I release objects in -(void)viewDidUnload rather than in -dealloc?

Basically, in viewDidUnload you release objects that you've created in the beginning of view's life cycle (loadView, viewDid load and so on). So if your viewController receives memory warning it will unload a view and reload it again and then your objects will be released in viewDidUnload and initialized again in loadView/viewDidLoad/ect

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜