I am assuming that somewhere in my code the objects in the array are being removed faster than they are created. I have been looking for the problem for over an hour so please help!
Here is the error:*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 7 beyond bounds [0 .. 6]'
Thanks in advance and here is my code:
- (void)onTimer {
UIImageView *imgView = [[UIImageView alloc] init];
imgView.image = particleImg;
imgView.frame = CGRectMake(kViewDimensions/2, kViewDimensions/2, startSize.width, startSize.height);
[self addSubview:imgView];
[particlesArray addObject:imgView];
[imgView release];
moveTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(moveObjs) userInfo:nil repeats:YES];
}
- (void)moveObjs {
for (int i = 0; i < [particlesArray count]; i++) {
animID = @"MoveId";
UIImageView *imgV = [particlesArray objectAtIndex:i];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
CGPoint randPoint = CGPointMake(arc4random()%kMaxRandX, arc4random()%kMaxRandY);
imgV.center = CGPointMake(randPoint.x, randPoint.y);
[UIView commitAnimations];
animValue = i;
num = [NSNumber numberWithInt:animValue];
[NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(animationEnded) userInfo:num repeats:NO];
NSLog(@"\n %d",animValue);
}
}
- (void)animationEnded {
int av = [num intValue];
UIImageView *iv = [particlesArray objectAtIndex:av];
if ([animID isEqualToString:@"MoveId"]) {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.1];
iv.alpha = 0.0f;
[UIView commitAnimations];
[particlesArray removeObjectAtIndex:av];
}
else {
[iv removeFromSuperview];
}
}
Attempting to trigger a method at the end of your animation with a timer is ill-advised. Instead, you should be using the
setAnimationDidStopSelector:class method within your animation block. On top of that, because of the way you are using num to handle removing objects from the array, you are guaranteed to exceed the bounds of the array at some point during one of the invocations of animationEnded. It would be better to reference the object itself, rather than its position in the array. This is what the context parameter in thebeginAnimations:context:method is for:NOTE: If you are not supporting versions prior to iOS 4, then you should switch to using the new Blocks based methods, such as
animateWithDuration:animations:completion:.