开发者

how much to release in viewDidUnload

开发者 https://www.devze.com 2023-03-30 15:58 出处:网络
The Apple template provides this comment in the viewDidUnload: // Release any retained subviews of the main view.

The Apple template provides this comment in the viewDidUnload:

// Release any retained subviews of the main view. // e.g. self.myOutlet = nil;

So I typically set IB Outl开发者_如何学运维ets to nil in viewDidUnload then release them in dealloc. The question is, all my other retained ivar objects, some of which are views that were added programmatically, while others are data models, should they also be dealt with in these two methods? If not, why not?

from this answer here i gather that only view-related objects should go in viewDidUnload as =nil statements, which should probably include non-IB Outlet retained views, correct? Then, all other objects, included data models, should go in dealloc as release statements. Is this the normal practice?


viewDidUnload is called as a result of a low memory condition to unload the view for a view controller that is not currently visible. At this point the view object of the view controller has been released which means all the objects that are subviews of viewController.view have been released, but they are not deallocated if you are retaining them in your ivars.

You should release any object that will be recreated when the view is loaded again or things you can easily recreate as needed. The next time the view is used the view will be recreated either from the NIB or by calling loadView so all those things you release will be recreated.

When your view comes from a NIB all the view objects specified in the NIB are created and added as subviews of the view controller's view. Any ivars with IBOutlets are also connected to those subviews so that you also "own" those objects (you have a retain on them). You need to release those ivars so that they will actually get dealloc'd.

When your view is created programatically in loadView you should also release those object retained by your ivars that will be recreated in loadView the next time the view loads.

Same for anything you create in viewDidLoad (or viewWillAppear or elsewhere), such as data models, if you can recreate it "easily" later when the view loads again or when the object is needed then it should be released in viewDidLoad to reduce memory usage. Actually for non-view items, like a data model, I would release it in didReceiveMemoryWarning instead.

Assigning nil to a retained property using the setter causes a release to be sent to them, when you write self.myOutlet = nil you are invoking the setter method which is implemented something like this:

-(void)setMyOutlet:(id)newObject
{
    [newObject retain];     // does nothing if newObject is nil
    [myOutlet release];    
    myOutlet = newObject;
}
0

精彩评论

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

关注公众号