Ios 释放消息到UINavigationController对象

Ios 释放消息到UINavigationController对象,ios,cocoa-touch,memory-management,uinavigationcontroller,Ios,Cocoa Touch,Memory Management,Uinavigationcontroller,我对Cocoa编程比较陌生,内存管理的某些方面仍然困扰着我 在本例中,我使用alloc消息创建UINavigationController,并使用UIView控制器初始化它。然后,我通过将视图传递给presentModalViewController方法来显示视图。代码如下: - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {

我对Cocoa编程比较陌生,内存管理的某些方面仍然困扰着我

在本例中,我使用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];
}
根据retain count规则,如果我将消息“alloc”发送给一个类,那么该类的一个实例将返回retain count 1,我负责释放它。在上面的代码中,我在将newPropertyNavigationController实例传递给modalViewController并呈现它之后,释放了它。当我关闭模式视图时,应用程序崩溃

如果我注释掉最后一行,应用程序不会崩溃

为什么会这样?UINavigationController的特定alloc/init消息的工作方式是否与其他类中的工作方式不同,即,它是否可能返回自动释放的实例

谢谢


彼得

你需要停止你正在做的事情,通读一遍。内存管理的规则非常简单易懂。让它们烧到你的头上(不会花很长时间)。然后逐行检查故障点中的代码,以及从代码中调用的API。以这种方式跟踪代码,而规则在您的头脑中是新鲜的,这将帮助您解决内存问题,并且可能,只是可能,帮助您防止将来出现这些问题。

创建模式视图控制器的方式看起来是正确的。检查模态视图控制器上dealoc的实现,以查看问题是否存在

如果不正确地删除内存,它将解释为什么只有在释放模态视图控制器时才会出现错误

作为参考,我发现下面使用autorelease更具可读性和可维护性

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];

在初始化UINavigationController对象之前,不要自动释放它。您不应该向未初始化的对象发送任何消息,初始化该对象的消息除外。
autorelease
消息应位于
initWithRootViewController:
消息之后。(编辑错误?)彼得·霍西:啊,是的。打字错误修正。谢谢你解决了这个问题。正如您所建议的,我查看了newProperty对象,发现在dealloc方法中,我将dealloc消息发送到对象的属性,而不是释放消息。这是一个令人尴尬的错误,但确实如此。谢谢你的帮助,非常感谢。谢谢你的指点,彼得,这对发现问题帮助很大。见我对Acusee评论的回复。