我对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];
}
根据保留计数规则,如果我将消息“alloc”发送给一个类,则该类的实例将返回保留计数为1,并负责释放它。在上面的代码中,在将newPropertyNavigationController实例传递给modalViewController并呈现之后,我将其释放。当我关闭模式视图时,应用程序崩溃。
如果我在最后一行注释掉,则该应用程序不会崩溃。
为什么会这样呢?是给UINavigationController的特定alloc / init消息是否不同于它在其他类中的工作方式,即。也许返回一个自动释放的实例?
谢谢!
彼得
最佳答案
您创建模态视图控制器的方式看起来正确。检查模式视图控制器上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];
关于ios - 将消息发布到UINavigationController对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3278532/