OGeek|极客世界-中国程序员成长平台

标题: iphone - 对象 dealloc 仅在 iOS 4.3 中崩溃 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 10:23
标题: iphone - 对象 dealloc 仅在 iOS 4.3 中崩溃

我试图弄清楚为什么使用 didSelectRowAtIndexPath 在我的 tableView 中推送 viewController 会导致 iOS 4.3 中的崩溃,但在 iOS 5.0+ 中,它可以正常工作。

当我打电话时它就崩溃了:

self.customViewController = [[[CustomViewController alloc] initWithNibName"CustomViewController"bundle:nil] autorelease];

第一次推送 customViewController 之后的任何时间。

这是我的相关代码:

@property (nonatomic, retain) CustomViewController *customViewController;

-(void) dealloc // Dealloc of tableView.
{

[customViewController release];
customViewController = nil;

}


- (void)tableViewUITableView *)tableView didSelectRowAtIndexPathNSIndexPath *)indexPath
{

self.customViewController = [[[CustomViewController alloc] initWithNibName"CustomViewController"bundle:nil] autorelease]; // Release old, allocate new, set it.

[[self navigationController] pushViewController:customViewController animated:YES];
[customViewController release]; // Balance out pushViewController's retain.


}

谢谢。



Best Answer-推荐答案


- (void)tableViewUITableView *)tableView didSelectRowAtIndexPathNSIndexPath *)indexPath
{
self.customViewController = [[[CustomViewController alloc] initWithNibName"CustomViewController"bundle:nil] autorelease];
[[self navigationController] pushViewController:customViewController animated:YES];
[customViewController release]; // Balance out pushViewController's retain. ---->NO
}

最后一个release是多余的,不需要。
您已经对其进行了 autorelease 以使其 retain count 减一。


我们将分析这一行

self.customViewController = [[[CustomViewController alloc] initWithNibName"CustomViewController"bundle:nil] autorelease];

你创建一个 CustomViewController 保留计数 == 1。
您在上面说 autorelease 所以保留计数稍后会为 0(可能是运行循环的结尾),但现在它仍然是 1 这就是为什么您仍然可以访问它,但将其视为 0 .
之后你说self.customViewController,那个属性是retain,所以retain count == 1。 你正在处理你的 dealloc 中的那个 1。
根据您的评论:

// Balance out pushViewController's retain.

你不Balance那些,你只平衡一个你拥有的。如果系统对您的对象进行保留,当系统不再需要它们时,它会释放它们。

关于iphone - 对象 dealloc 仅在 iOS 4.3 中崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8638836/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4