iOS: When is best to deallocate a model object in a view controller?
I've got a fairly basic question here. I find that quite often I instantiate model objects in the viewDidLoad: method of view controllers, say in the case of a web service object that is used to populate the elements of a table in the view controller:
- (void)viewDidLoad {
[super viewDidLoad]; 开发者_JS百科
itemService = [[BlogItemService alloc] init];
}
Where should I release itemService? In viewDidUnload or dealloc?
Furthermore, is it common to allocate objects like this in viewDidLoad? Is there not a more suitable init type method?
Update: I have a particular concern. Let's say I deallocate itemService in dealloc. If the view is unloaded and then reloaded, but the view controller is not deallocated, won't I have a memory leak as the previous instance of itemService is orphaned when the new one is instantiated?
Where should I release itemService? In viewDidUnload or dealloc?
if the object is lightweight or takes a long time to create, do it in dealloc. if it consumes a lot of memory, then use matching pairs in viewDidLoad/viewDidUnload.
Furthermore, is it common to allocate objects like this in viewDidLoad?
yes
Is there not a more suitable init type method?
the designated initializer (in some cases)
Update: I have a particular concern. Let's say I deallocate itemService in dealloc. If the view is unloaded and then reloaded, but the view controller is not deallocated, won't I have a memory leak as the previous instance of itemService is orphaned when the new one is instantiated?
to avoid this, use:
BlogItemService * item = [[BlogItemService alloc] init];
self.itemService = item;
[item release], item = nil;
It is very uncommon situation, but if you unload and then load view again you will have leak just as you suggested. So where to allocate objects it is a good question and it rather depends on your choice. Probably it is better to load objects every time view is loaded when they are very heavy and some small objects will probably be easier to load in init. But you have also handle your view controller carefully if you want to load and unload view many times, beacuse common pattern is to destroy controller every time the view dissapears (and mostly it is a good solution).
You should release the object in dealloc
You can allocate memory using :
itemService=[BlogItemService new];
If you would ask me the best place to initialize model objects is in the init
method of the class and release
it in dealloc
.
精彩评论