2012-02-10 148 views
0

今天我做了一些測試,我很好奇的結果。我做了一個應用程序(ARC),它有UINavigationController和兩個UIViewControllers。在第一個視圖中有一個按鈕,當按下該按鈕時,將加載第二個視圖。在第二個視圖中,當檢測到搖晃手勢時,加載第一個視圖,依此類推。我在文書中注意到,每次加載視圖時,堆都會增長。下面是一些代碼堆內存越來越大

AppDelegate.m

self.navigationController = [[UINavigationController alloc]init]; 
self.window setRootViewController:self.navigationController]; 
FirstViewController *firstview = [FirstViewController alloc]init]; 
[self.navigationController pushViewController:FirstViewController animated:YES]; 

FirstViewController.m

-(IBAction)loadSecondView 
{ 
    SecondViewController *secondview = [SecondViewController alloc]init]; 
    [self.navigationController pushViewController:secondview animated:YES]; 
} 

SecondViewController.m

-(IBAction)loadFirstView 
{ 
    FirstViewController *firstview = [FirstViewController alloc]init]; 
    [self.navigationController pushViewController:first view animated:YES]; 
} 

我想不通,爲什麼出現這種情況。在這種情況下如何避免堆積如山?

+0

在你的第二個的viewController有將已經後退按鈕,當你點擊就可以了,所以沒必要實施loadFirstView method.because每次你被creatng FirstViewController的新實例時自動工作,這就是爲什麼內存堆中成長每次。 – 2012-02-10 08:55:57

+0

我不想那個按鈕。我想在檢測到搖晃手勢時工作。 – objlv 2012-02-10 08:58:43

+0

搖:[self.navigationController popViewControllerAnimated:YES]; – NeverBe 2012-02-10 09:09:38

回答

1

其實每次你創建一個新的視圖控制器對象的時間..這不應該做的。

所以每次分配一個新對象,並推動這一觀點的時候,它會被添加到導航棧,因此,存儲的增長。

相反,當您處於第一個視圖並點擊該按鈕時,您可以彈出當前視圖控制器並通知AppDelegate類顯示第二個視圖。

同樣在第二個視圖中,當您想要顯示第一個視圖時,彈出當前視圖並通知AppDelegate類推入第一個視圖控制器。

+0

你能告訴我一些簡單的例子嗎? – objlv 2012-02-10 09:05:11

0
SecondViewController *secondview = [[[SecondViewController alloc]init] autorelease]; 

FirstViewController *firstview = [[[FirstViewController alloc]init] autorelease]; 

如果第二控制器打開第一,你應該自動釋放viewcontrollers(不ARC)

,你應該做的popViewController。如果你不會回國了堆將增長