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