0

我尝试管理多个视图并将这些引用保存在一个可变数组中。如果我既在可变数组中添加视图引用,又添加到视图中,作为子视图。然后引用计数似乎不正确。会导致bad access错误。

所以我的问题是,是否有管理这些视图的好方法。例如,如果我需要重用视图。不使用时将它们保存在可变数组中,并在以后重用它们。

编辑:

    NSMutableArray* reuseViews = [NSMutableArray arrayWithCapacity:0];
    for (int i=0; i<3; i++) {
        UIView* v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
        [reuseViews addObject:v];
        [self.view addSubview:v];
    }

    for (int i=0; i<3; i++) {
        UIView* v = [reuseViews objectAtIndex:i];
        [v removeFromSuperview]; // it also removes the reference in the array
        [reuseViews removeObject:v]; // will crash
    }
4

1 回答 1

2

for尝试删除第三个项目时,第二个循环将崩溃。这是因为 的值为i2,索引中的项目数为 1。当您尝试将对象拉出数组时,它会崩溃。

要解决此问题,请等到循环之后删除所有对象:

for (int i=0; i<3; i++) {
    UIView* v = [reuseViews objectAtIndex:i];
    [v removeFromSuperview];
}

[reuseViews removeAllObjects];

更好的是使用快速枚举:

 for (UIView* v in reuseViews) {
    [v removeFromSuperview];
}

[reuseViews removeAllObjects];
于 2013-09-15T03:53:48.353 回答