2011-06-10 71 views
8

許多人在視圖控制器的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

回答

3

不,這是沒有必要的,dealloc,你正確地說,會爲你做:)(長篇,簡答)。

1

我發現它在我的項目中是必需的。我的viewController有一個主視圖(因爲他們都這樣做),在這種情況下,它是使用xib定義的(不是以編程方式分配和添加爲子視圖)。該視圖在視圖控制器中具有IBOutlets的子視圖。如果在viewDidUnload上,我簡單地將IBOutlet屬性設置爲nil(self.mySubView = nil),那麼不調用該子視圖上的dealloc。如果我先從它的超視圖(主視圖)中刪除它,則調用dealloc。

+1

你有任何示例代碼來說明這一點嗎?既然你提到了XIB,那麼把這個項目放在Github上會更有幫助。謝謝。 – 2012-05-18 18:40:46

相關問題