Should I place my activity indicator release statement in dealloc?
I have a pretty simple question. In the following piece of code, is it better to place the activity indicator in the dealloc since I am starting and stopping the activity indicator after it is added to subview?
- (void)viewDidLoad {
[super viewDidLoad];
// add activity indicator
activityIndicator = [[UIActivityIndicatorView开发者_Python百科 alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.center = CGPointMake(self.view.bounds.size.width / 2.0f, self.view.bounds.size.height / 2.0f);
activityIndicator.hidesWhenStopped = YES;
[self.view addSubview:activityIndicator];
[activityIndicator release]; // SHOULD THIS BE PLACED IN DEALLOC?
[self loadFax];
}
Actually, I would place the release in viewDidUnload, besides dealloc.
Not doing so could result in a memory leak in case your app receives a memory warning and all of it's views are released; indeed, in this case the view would be loaded once again when needed and this would cause a second allocation for you activity indicator, without the previous instance being released.
Keep in mind, as per comment below, that releasing in viewDidUnload does not mean you may skip releasing in dealloc. This for two reasons: if you are running iOS 2.x there is no viewDidUnload; furthermore, when your view controller is released normally, viewDidUnload will not be called. So the suggestion is doing in both places and do not forget to set the ivar value to nil after doing it.
In this case, it would be better to release as you are doing, but then at least set the ivar value to nil, otherwise you could think you own the object still.
If you used a retain property and made the assignment like this:
Self.activityIndicator = ....
This would not be the case, still I think that releasing in viewDidUnload what you created in viewDidLoad is better practice in general.
Here what the docs about viewDidUnload.
Yes, if you plan on using the activityIndicator throughout your view at random times, dealloc
would be a good place for it.
I would release it as it is used, creating a new one every time I needed it. That way you don't have an allocated chunk of memory sitting around useless. Make yourself a delegate of the indicator and release it as it finishes.
精彩评论