当addSubview和removeFromSuperview时堆增长

时间:2012-02-21 20:35:42

标签: iphone xcode memory-management addsubview

当我添加子视图并返回到父级时,我在“乐器分配”中看到了HEAP GROWTH和PERSISTENT元素的问题。子视图是一个简单的空白视图,后面的按钮由IB添加。

在乐器中,当我使用“标记堆”重复相同动作6次时,我看到了这一点。 cicle是:点击父级中的按钮添加子视图并返回子视图中的父级点击后退按钮:

enter image description here

我认为这将是零!这是一个非常简单的行动。

我用来在View1Controller.m中加载子视图的代码是:

View2Controller *jv;    
jv = [[View2Controller alloc] initWithNibName:nil bundle:nil];
[self.view addSubview:jv.view]; 

在View2Controller.m中我回去了

-(IBAction) Back {
    [self.view removeFromSuperview];
    self.view = nil;
}

我做错了什么?

提前致谢。

2 个答案:

答案 0 :(得分:2)

当您使用[self.view removeFromSuperview];时,self.view与其超级视图取消关联,但未发布。因此内存占用增长。

为了避免内存泄漏,您应该通过调用View1Controller.m文件中创建的View2Controller实例上的release方法来释放内存。

例如,您可以记住对通过设置属性创建的View2Controller实例的引用(在此示例中为jv属性):

View2Controller *view2controllerInstance = [[View2Controller alloc] initWithNibName:nil bundle:nil]; // create the new instance
self.jv = view2controllerInstance; // memorize the reference
[view2controllerInstance release]; // release the property on view2controller
[self.view addSubview:self.jv.view]; // add the subview

应使用声明属性定义jv属性,如下所示:

@property (retain, nonatomic) View2Controller *jv;

答案 1 :(得分:0)

在你的第二个代码块中:

-(IBAction) Back {
    [self.view removeFromSuperview];
    self.view = nil;
}

如果这是您View2Controller中的代码,那么您遇到问题的原因是因为您正在将视图指针设置为nil,然后视图才能正确释放自身。在它自己的dealloc阶段,它将释放视图并正确删除Interface Builder Elements。尝试删除或注释掉self.view = nil;行。

相关问题