是否有正确的方法来释放存储在NSMutableArray中的视图?

时间:2012-02-20 19:52:16

标签: objective-c memory-management nsmutablearray

我的程序向屏幕添加了无限量的视图(由用户在运行时确定),并通过将它们存储在数组中来跟踪这些视图。

在我的视图控制器中

for (NSString *equationText in equationData) {

// creates a FormulaLabel object for every object in the equationData mutable array 

FormulaLabel *tempLabel = [[FormulaLabel alloc] initWithFrame:CGRectMake(frame)];
[view addSubview:tempLabel];
[balanceItems addObject:tempLabel];  //balance items keeps track of all the views

当我更新数据时,我需要在屏幕上显示不同的视图,所以我认为反映数据更改的最快方法是删除当前屏幕上的所有视图并从更新的数据中添加新视图

对于这种方法,(据我所知)我需要从superview中删除视图,释放它们,并删除存储在balanceItems中的对象。然后我需要初始化新视图,将它们添加到子视图,然后将它们添加到数组中。但是,下面的代码会生成错误。

for (UIView *view in balanceItems) {

    [view removeFromSuperview];
    [view release];
}

[balanceItems removeAllObjects];

从superview和数组中删除视图的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

首先,您应该在创建视图时正确发布视图:

FormulaLabel *tempLabel = [[FormulaLabel alloc] initWithFrame:CGRectMake(frame)]; // retain count is 1
[view addSubview:tempLabel]; // retain count is 2
[balanceItems addObject:tempLabel]; // retain count is 3
[tempLabel relase]; // retain count is 2

你应该释放tempLabel,因为你是用init方法获得的,所以你拥有它。

然后当你删除视图;你不必致电发布:

for (UIView *view in balanceItems) {
    [view removeFromSuperview]; // retain count is 1
}
[balanceItems removeAllObjects]; // retain count is 0 => view gets deallocated

因为视图当前只保留了超级视图和数组,所以当你从它们中删除它时它将被释放。

相关问题