【问题标题】:UIViewController pushViewController high retain count of View controllerUIViewController pushViewController 高保留视图控制器的数量
【发布时间】:2012-03-04 12:51:00
【问题描述】:

我写了以下代码:

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

GameViewController *gameViewController = [[GameViewController alloc]initWithLevelNumber:([levelGroup intValue]*100+indexPath.row) Bonus:NO];

NSLog(@"Retain Counter =%d",gameViewController.retainCount);

[navController pushViewController:gameViewController animated:YES];
[gameViewController release];

NSLog(@"Retain Counter=%d",gameViewController.retainCount);

[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

两个日志的结果依次为16! 这怎么可能?我只调用一次alloc方法并在将控制器压入堆栈后释放.. alloc-> +1,push-> +1,release-> -1 = 1?

当我将视图控制器从堆栈中弹出时,我希望它被释放。

【问题讨论】:

  • 尝试将其更改为自动释放,看看会发生什么
  • 不要使用retainCount 来检查泄漏。使用仪器工具。搜索“retaincount”,你会发现很多很多原因,为什么它在 99% 的时间里都是一个糟糕的属性。在有用的 1% 的时间里,这不值得麻烦。

标签: objective-c ios uinavigationcontroller pushviewcontroller retaincount


【解决方案1】:

请阅读此说明以明确此问题。它是 NSObject 协议参考的一部分:

重要提示:此方法在调试内存管理问题时通常没有价值。因为任意数量的框架对象可能已经保留了一个对象以保存对它的引用,而同时自动释放池可能在一个对象,您不太可能从该方法中获得有用的信息

NSObject Protocol Reference. RetainCount discussion

【讨论】:

  • 我希望更多人对此投赞成票。 retainCount 是无用的属性,不应该出现在公共 SDK 中。
【解决方案2】:

自动释放您的 GameController 创建,如下所示:

GameViewController *gameViewController = [[[GameViewController alloc]initWithLevelNumber:([levelGroup intValue]*100+indexPath.row) Bonus:NO] autorelease];

然后删除[gameViewController release];然后你的代码看起来很干净,gameViewController 将在从导航堆栈中弹出后自动释放。不用担心retainCount - 当您推送视图控制器时,UIKit 会接管并会在需要时将retain/release 处理。你只需要担心你的代码。其实你写的方式应该没问题,我只是觉得我这里的建议让代码更干净。

除非您在 Instruments 中看到您的 gameViewController 对象存在内存泄漏,否则我认为您不必担心。

【讨论】:

    【解决方案3】:

    这是因为内部有一些retain(通过pushViewController:方法),你不应该检查retain count,只检查你释放了你拥有的对象,尤其是当你检查sdk调用方法之间的retain count时。

    【讨论】:

      【解决方案4】:

      你在你的 GameViewController 中使用 NSNotificationCenter 吗? 可能是您将视图控制器作为观察者添加到 NotificationCenter 并增加了 retainCount。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-27
        • 1970-01-01
        • 2012-04-23
        • 1970-01-01
        • 2017-04-23
        • 2013-07-04
        • 2017-09-09
        • 1970-01-01
        相关资源
        最近更新 更多