开发者

why do I see some code where stuff is released in viewDidUnload as opposed to dealloc?

All the tutorials I have done say that I set stuff to nil in viewDidUnload and then release in dealloc. However I am being told that t开发者_如何学运维his would cause a memory leak since viewDidUnload gets called before a dealloc and so I am unable to release anything that is set to nil.

Can someone help clarify?


If you create an object (with alloc and init) in viewDidLoad, then you should release it in viewDidUnload. The reason is that sometimes viewDidUnload is called to save memory, but dealloc is not called. Then, later, viewDidLoad may be called again. In general, release anything you allocate in the inverse method, e.g.

If you allocate an object in init, then release it in dealloc.

If you allocate an object in viewDidLoad, then release it in viewDidUnload.

If you allocate an object in viewWillAppear (or viewDidAppear), then release it in viewWillDisappear (or viewDidDisppear).


Have a look at the answer given by @Sean in this previous SO question. He clearly states the purpose of releasing in viewDidUnload

One of the most important reasons for implementing it is that UIViewController subclasses commonly also contain owning references to various subviews in the view hierarchy. These properties could have been set through IBOutlets when loading from a nib, or programmatically inside -loadView, for instance.

The additional ownership of subviews by the UIViewController means that even when its view is removed from the view hierarchy and released to save memory, through which the subviews are also released by the view, they will not actually be deallocated because the UIViewController itself still contains its own outstanding retaining references to those objects as well. Releasing the UIViewController's additional ownership of these objects ensures they will be deallocated as well to free memory.

The objects that you release here are usually recreated and set again when the UIViewController's view is re-loaded, either from a Nib or through an implementation of -loadView.

Also note that the UIViewController's view property is nil by the time this method is called.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜