許多人在視圖控制器的viewDidUnload
方法中說,您必須通過調用removeFromSuperview
方法來刪除子視圖。例如,Three20做這樣的事情:在視圖控制器中,在viewDidUnload期間是否需要在子視圖上調用removeFromSuperview?
- (void)viewDidUnload {
[super viewDidUnload];
... snipped ...
[_tableBannerView removeFromSuperview];
TT_RELEASE_SAFELY(_tableBannerView);
[_tableOverlayView removeFromSuperview];
TT_RELEASE_SAFELY(_tableOverlayView);
... snipped ...
}
我理解這種想法背後的原因:如果您在loadView
叫[self.view addSubview:_aView]
,你應該叫在viewDidUnload
[_aView removeFromSuperview]
。事情是,這似乎沒有必要。當視圖控制器的視圖被釋放時,它的dealloc方法會自動釋放它的所有子視圖。我的測試代碼顯示在他們的上海華得到釋放子視圖自動獲得釋放:
@interface TestView : UIView
@end
@implementation TestView
- (id)retain {
NSLog(@"view retain");
return [super retain];
}
- (void)release {
NSLog(@"view release");
[super release];
}
- (id)init {
NSLog(@"view init");
return (self = [super init]);
}
- (void)dealloc {
NSLog(@"view dealloc");
[super dealloc];
}
@end
@interface TestViewController : UINavigationController
@end
@implementation TestViewController
- (void)loadView {
NSLog(@"viewController loadView");
[super loadView];
[self.view addSubview:[[TestView new] autorelease]];
}
- (void)viewDidUnload {
NSLog(@"viewController viewDidUnload");
[super viewDidUnload];
}
- (void)viewDidAppear:(BOOL)animated {
NSLog(@"viewDidAppear");
[super viewDidAppear:animated];
[self dismissModalViewControllerAnimated:YES];
}
- (void)dealloc {
NSLog(@"viewController dealloc");
[super dealloc];
}
@end
上面的代碼產生以下輸出:
viewController loadView
view init
view retain
view release
viewDidAppear
viewController dealloc
view release
view dealloc
正如你所看到的,當視圖控制器的主視圖得到釋放,它的子視圖也被釋放。
此外,iOS開發者庫[狀態](http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/BasicViewControllers/BasicViewControllers.html#//apple_ref/doc/uid/TP40007457-CH101 -SW4 ):「在內存不足的情況下,默認的UIViewController行爲是釋放存儲在視圖屬性中的視圖對象,如果該視圖當前未被使用。」另外:「如果您使用聲明的屬性來存儲對視圖的引用,並且該屬性使用保留語義,則爲其分配一個零值就足以釋放該視圖。」
那麼,如果釋放視圖會自動釋放它的子視圖,是否真的有必要在viewDidUnload
期間調用removeFromSuperview
?
你有任何示例代碼來說明這一點嗎?既然你提到了XIB,那麼把這個項目放在Github上會更有幫助。謝謝。 – 2012-05-18 18:40:46