2010-08-26 22 views
0

我的iPhone應用程序中有RootViewController和DetailsViewController。我使用Allocations工具來監視我的內存消耗,並且我有一個問題。我的應用程序啓動時需要大約4Mb的內存,當我在RootViewController中選擇項目時,它會在DetailsViewController中加載UIWebView並且內存上升到10Mb,在我返回RootViewController內存後保持在10Mb級別,DetailsViewController的內存爲retainCount = 2(即使我只創建一次)。何時發佈detailsViewController

我該如何釋放這些內存?我知道我應該這樣做,如果我的應用程序收到內存警告,但我使用initWithNibName:創建此ViewController,所以我明白我不應該發送release它。

謝謝。

編輯

我加載它是這樣的:

if (self.detailsViewController == nil) 
{   
detailsViewController *d = [[detailsViewController alloc] 
     initWithNibName:@"DetailsViewController" 
     bundle:[NSBundle mainBundle]]; 

self.detailsViewController = d; 
[d release]; 

self.detailsViewController.urlToLoad = urlToLoad; 
} 
[self.navigationController pushViewController: self.detailsViewController animated:YES]; 
+0

DetailsViewController應該有一個retainCount爲1,因爲它是一個新對象,你如何加載這個Nib? – 2010-08-26 12:01:53

+0

如果detailsViewController屬性聲明爲retain(我認爲是),那麼你需要釋放它,可能在dealloc中。 – taskinoor 2010-08-26 13:07:44

+0

請參閱下面的答案。按下後應該釋放控制器。 – tobiasbayer 2010-08-26 13:17:54

回答

1

是否使用

DetailViewController *dvc = [[DetailViewController alloc] initWithNibName:NIB_NAME bundle:[NSBundle mainbundle]];

然後,你必須釋放DVC。記住alloc。

同樣使用泄漏來發現可能的泄漏。當你不需要它們時,你應該總是釋放你擁有的物體。不只是當你收到內存警告。

+0

是的,我正在做 – Burjua 2010-08-26 13:17:30

1

你是如何顯示你的DetailsViewContoller?通過pushViewController:...?如果是的話,你應該推之後立即發佈它,因爲pushViewController:...保留它。

+0

這一個更一般的評論 - 我發現XCode的「構建和分析」有助於標記代碼中的內存問題(比預期更多\少於保留次數和潛在內存泄漏)。 – TanvirK 2010-08-26 12:58:26

+0

好的,謝謝,我不知道這一點,但如果我推後釋放它沒有返回後設置爲零,retainCount = 1,但應用程序崩潰,下一次我點擊任何項目 – Burjua 2010-08-26 13:23:02

+0

在'DetailViewController'一下任何項目?很難確定問題出在哪裏,而沒有看到其他代碼。 – tobiasbayer 2010-08-26 13:51:03

1

有些代碼會對此有所幫助 - 否則我們只是猜測你在做什麼。

一般來說,當您將UIViewController添加到UINavigationController時,該ViewController將被保留,並且您應該釋放它。如果您將UIViewController的VIEW添加爲另一個視圖的子視圖,則該VIEW將被保留,但不會保留ViewController。底線:如果你說alloc爲任何東西,那麼你以後再欠它release。這是規則。還有copynew,以及任何你明確的retain

我強烈建議您不要自己跟蹤保留次數。由於與你的課程中發生的事情很少有關的原因,事情會被保留下來並在幕後發佈,你會看到這些數字以非常混亂的方式轉移。最佳做法是確保您的代碼餘額保留和發佈。你所有的括號必須平衡,對吧?所以你所有的分配和釋放。只是編譯器爲你檢查其中的一個,而你自己爲另一個檢查。

1

試試這個。 detailsViewController = nil; DetailsViewController * d = [[DetailsViewController的alloc] initWithNibName:@ 「DetailsViewController」 束:一個NSBundle mainBundle]];

self.detailsViewController = d; 
[d release]; 

detailsViewController.urlToLoad = urlToLoad; 
} 
[self.navigationController pushViewController: detailsViewController animated:YES]; 
[detailsViewController release]; 
+0

是的,我做的完全一樣的寫現在,應用程序崩潰時我嘗試做第二次,我解決了這個問題,將'detailsViewController =零;' 現在我有如下描述確切的問題:HTTP:// stackoverflow.com/questions/2950907/uiwebview-memory-management有沒有解決方案? – Burjua 2010-08-26 14:58:36