何时从UITableViewController创建时释放UINavigationController?

时间:2012-09-13 06:25:34

标签: ios

我有一个相当不寻常的情况,我不太了解内存管理。

我有一个UITableViewController用于显示消息,然后创建一个UINavigationController并将其视图添加为当前视图的子视图以显示它。我遇到的问题是Xcode报告我有一个潜在的内存泄漏(我同意)由于没有释放UINavigationController,但是当我在下面的代码中发布它时,当我点击返回以返回到应用程序时应用程序崩溃表视图。

我在UITableViewController中使用了一个保留属性来跟踪当前的UINavigationController并管理保留计数,但显然我在这里遗漏了一些东西。

注意:单击“返回”按钮并显示消息时发生崩溃 - [UILayoutContainerView removeFromSuperview:]:无法识别的选择器发送到实例0x5537db0

另请注意,如果我删除[nc release]代码行,它就可以正常工作。

这是我的代码:

@property(nonatomic, retain) UINavigationController *currentNavigationController;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UINavigationController *nc = [[UINavigationController alloc] init];

    CGRect ncFrame = CGRectMake(0.0, 0.0, [[self view] frame].size.width, [[self view] frame].size.height);
    [[nc view] setFrame:ncFrame];

    // I created a CurrentNavigationController property to 
    // manage the retain counts for me
    [self setCurrentNavigationController:nc]; 

    [[self view] addSubview:[nc view]];
    [nc pushViewController:messageDetailViewController animated:YES];


    UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonSystemItemRewind target:[nc view] action:@selector(removeFromSuperview:)];


    nc.navigationBar.topItem.leftBarButtonItem = bbi;
    [bbi release];

    [nc release];
}

1 个答案:

答案 0 :(得分:1)

您创建的UINavigationController“nc”仅在此方法中可用。在此方法之后它不存储在任何地方(因为您释放它)。因此,您将navigationController的视图作为子视图添加到类视图中,然后删除navigationController。那是错的。当views和viewControllers尝试引用他们的navigationController(当它不存在时),你的应用程序将崩溃。

这是didSelectRowForIndexPath方法的代码:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{

    UINavigationController *nc = [[UINavigationController alloc] init];

    CGRect ncFrame = CGRectMake(0.0, 0.0, [[self view] frame].size.width, [[self view] frame].size.height);
    [[nc view] setFrame:ncFrame];

    [self setCurrentNavigationController:nc]; 
    [nc release];

    [[self view] addSubview:[self.currentNavigationController view]];

    UIViewController *viewCont = [[UIViewController alloc] init];
    [viewCont.view setBackgroundColor:[UIColor greenColor]];

    [nc pushViewController:viewCont animated:YES];

    NSLog(@"CLASS %@",[[self.currentNavigationController view]class]);

    UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonSystemItemRewind target:[self.currentNavigationController view] action:@selector(removeFromSuperview)];


    self.currentNavigationController.navigationBar.topItem.leftBarButtonItem = bbi;
    [bbi release];
}

removeFromSuperview方法的选择器最后不应该有“:”。它没有参数:)