1

我有一个名为 imgBall 的 NSArray,它包含一个名为 imgView 的临时变量,当用户触摸屏幕上的某个点时,它会在屏幕上显示一个图像。

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(40, 40, 40, 40)];
    imgView.image = [UIImage imageNamed:@"ball.png"];
    [self.view addSubview:imgView];
    imgView.center = [myTouch locationInView:self.view];
    [imgBall addObject:imgView];
}

用户可以通过触摸屏幕上的任意位置来创建多个实例。可能意味着阵列中有 5、10 或 20 个不同的球。

现在,我有一个需要“清除”屏幕并删除所有 imgView 实例的按钮。我尝试了以下方法:

 for (UIImageView *imgView in imgBall) {
    [self.view removeFromSuperview:imgView]; 
}

    for (UIImageView *imgView in imgBall) {
    [imgBall removeObject:imgView];
}

但它们都产生 SIGABRT 并抛出异常:

Terminating app due to uncaught exception 'NSGenericException', reason: 
'*** Collection     <__NSArrayM: 0x735f4a0> was mutated while being enumerated.'

我有什么方法可以做到这一点而不会每次都抛出 SIGABRT?

4

3 回答 3

2

我想你想要:

for (UIImageView *imgView in imgBall) {
    [imgView removeFromSuperview]; 
    [imgBall removeObject:imgView];
}

在touchesEnded中创建的时候还需要在[imgBall addObject:imgView]之后做[imgView release],否则会泄漏内存。

于 2012-07-18T19:14:39.783 回答
1

这样做:

for (UIImageView *imgView in imgBall)
{
[imgView removeFromSuperview];
}

然后不要忘记释放并将数组 imgBall 设置为 nil 以避免内存问题。如果它是 NSMutableArray,只需调用 removeAllObjects。

于 2012-07-18T19:17:57.330 回答
1

你应该这样做......

for (UIImageView *imgView in imgBall) {
    [imgView removeFromSuperview];
}
[imgBall removeAllObjects];
于 2012-07-18T19:23:00.127 回答