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];
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?
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).