我有一个名为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,我该怎样做?
答案 0 :(得分:2)
我想你想要:
for (UIImageView *imgView in imgBall) {
[imgView removeFromSuperview];
[imgBall removeObject:imgView];
}
在touchesEnded中创建[imgBall addObject:imgView]后,还需要执行[imgView release] ,否则会泄漏内存。
答案 1 :(得分:1)
这样做:
for (UIImageView *imgView in imgBall)
{
[imgView removeFromSuperview];
}
然后不要忘记释放并将数组imgBall设置为nil以避免内存问题。如果它是NSMutableArray,只需调用removeAllObjects。
答案 2 :(得分:1)
你应该这样做......
for (UIImageView *imgView in imgBall) {
[imgView removeFromSuperview];
}
[imgBall removeAllObjects];