What is the difference between dealloc and viewdidunload?
When should I release all the memo开发者_运维知识库ry I allocated in my program?
Because I only have a viewDidLoad method where I do my business. Should I leave dealloc empty and cleanup only in viewDidUnload?
'dealloc' is used when the object is ready to be freed (i.e., when retain count of the object becomes 0). And viewDidUnload is called when the view is unloaded, but it may not be freed immediately as the reference of the UIViewController is still stored by some other objects.
my personal preference is, for ojbects created by 'init', they are freed by 'dealloc', for objects created by 'viewDidLoad', they are freed by 'viewDidUnload'.
As the documentation of -viewDidUnload
says:
It is called during low-memory conditions when the view controller needs to release its view and any objects associated with that view to free up memory. Because view controllers often store references to views and other view-related objects, you should use this method to relinquish ownership in those objects so that the memory for them can be reclaimed. You should do this only for objects that you can easily recreate later, either in your viewDidLoad method or from other parts of your application. You should not use this method to release user data or any other information that cannot be easily recreated.
Typically, a view controller stores references to objects using an outlet, which is a variable or property that includes the IBOutlet keyword and is configured using Interface Builder. A view controller may also store pointers to objects that it creates programmatically, such as in the viewDidLoad method. The preferred way to relinquish ownership of any object (including those in outlets) is to use the corresponding accessor method to set the value of the object to nil. However, if you do not have an accessor method for a given object, you may have to release the object explicitly.
There is no mention -viewDidUnload
will call in -dealloc
, you shouldn't rely on it.
精彩评论