shiami
shiami

Reputation: 7264

iOS holding UIView references in a MutableArray with ARC

I try to manage several views and keep those references in a mutable array. If I both add a view reference in a mutable array and also added into a view, as a subview. And then the reference count seems not correct. Will cause the bad access error.

So my question is that is there a good way to manage those views. For example, if I need to reuse the views. Keeping them in a mutable array when no used and reuse them later.

EDIT:

    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
    }

Upvotes: 0

Views: 125

Answers (1)

BergQuester
BergQuester

Reputation: 6187

The second for loop will crash when trying to remove the third item. This is because the value of i will be 2 and the number of items in the index is 1. When you try to pull the object out of the array, it will crash.

To fix this, wait until after the loop to remove all objects:

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

[reuseViews removeAllObjects];

Even better would be to use fast enumeration:

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

[reuseViews removeAllObjects];

Upvotes: 2

Related Questions