1

我對Cocoa編程比較陌生,內存管理的某些方面仍然令我困擾。發佈消息給UINavigationController對象

在這種情況下,我使用alloc消息創建UINavigationController,並使用UIView控制器初始化它。然後,我通過將它傳遞給presentModalViewController方法來呈現視圖。下面是代碼:

- (void)tableView:(UITableView *)tableView 
accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath 
{ 
NSLog(@"Tapped on disclosure button"); 
NewPropertyViewController *newProperty = [[NewPropertyViewController alloc] 
              initWithDictionary]; 
newProperty.editProperty = [fetchedResultsController objectAtIndexPath:indexPath]; 
UINavigationController *newPropertyNavigationController = [[UINavigationController 
              alloc] 
              initWithRootViewController:newProperty]; 
[newProperty setPropertyDelegate:self]; 
[self presentModalViewController:newPropertyNavigationController animated:YES]; 

[newProperty release]; 
[newPropertyNavigationController release]; 
} 

根據保留計數規則,如果我發送消息「黃金」一類,這個類的一個實例與保留計數1回來了,我負責將其釋放。在上面的代碼中,我將newPropertyNavigationController實例傳遞給modalViewController並將其呈現後釋放它。當我解散模態視圖時,應用程序崩潰。

如果我註釋掉最後一行,應用程序不會崩潰。

這是怎麼發生的?對UINavigationController來說,特定的alloc/init消息的工作方式與它在其他類中的工作方式不同,即:它可能是返回一個autoreleased實例嗎?

謝謝!

彼得

回答

1

您創建模態視圖控制器的方式看起來是正確的。檢查模態視圖控制器上的dealloc實現,看看問題是否存在。

如果您錯誤地刪除了內存,它將解釋爲什麼您只有在釋放模態視圖控制器時纔會出現錯誤。

僅供參考,我覺得以下使用自動釋放的更多可讀性和可維護性

NewPropertyViewController *newProperty = [[[NewPropertyViewController alloc] 
             initWithDictionary] autorelease]; 
newProperty.editProperty = [fetchedResultsController objectAtIndexPath:indexPath]; 
UINavigationController *newPropertyNavigationController = [[[UINavigationController 
             alloc] 
             initWithRootViewController:newProperty] autorelease]; 
[newProperty setPropertyDelegate:self]; 
[self presentModalViewController:newPropertyNavigationController animated:YES]; 
+1

在初始化之前不要自動釋放UINavigationController對象。除了初始化消息之外,不應將任何消息發送給未初始化的對象。 'autorelease'消息應該出現在'initWithRootViewController:'消息之後。 (編輯錯誤?) – 2010-07-19 05:31:23

+0

@Peter Hosey:啊,是的。錯字固定。謝謝 – Akusete 2010-07-19 05:41:55

+0

發現問題。 正如你所建議的,我查看了newProperty對象,發現在dealloc方法中,我將dealloc消息發送給對象的屬性而不是釋放消息。這是一個尷尬的錯誤,但它是。 感謝您的幫助,我們對此表示感謝。 – futureshocked 2010-07-20 01:24:47

2

你需要停止你正在做什麼,通讀this。內存管理規則非常簡單易懂。讓它們燒到你的頭上(不需要很長時間)。然後在您的問題點中逐行檢查您的代碼,並從您的代碼中調用apis。當規則新鮮時,用這種方式追蹤代碼將幫助你解決你的記憶問題,或許也許可以幫助你在將來避免使用它們。

+0

感謝您的指針彼得,它幫助了很多找出問題所在。看到我對Acusete的評論的回覆。 – futureshocked 2010-07-20 01:22:08