Some code; I'll explain first:
I have a bullet Sprite which has a file of it's own and I manage things in my GameLayer, every time there's a touch event, I calculate speed and direction and I check within the sprite if it's out of the screen, if it is - a BOOL property is changed to YES.
I'm trying to iterate the children array of self for sprites of bullet, like so:
[self schedule:@selector(checkIfOut:)];
....
- (BOOL)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint loc = [touch locationInView:[touch view]];
loc = [[Director sharedDirector] convertCoordinate:loc];
Bullet *object = [Bullet node];
CGPoint pos = ccp(160.0, 24.0);
object.position = pos;
CGPoint velocity = ccp(loc.x - object.position.x, loc.y - object.position.y);
CGPoint direction = ccpNormalize(velocity);
velocity = ccpMult(direction, kSpeed);
object.velocity= velocity;
[self addChild:object];
return kEventHandled;
}
- (void)checkIfOut:(ccTime)dt {
for(Bullet *b in [self children]){
if(b.outOfScreen){
[self removeChild:b cleanup:YES];
}
}
}
But this gives me an error, as it gets into the for loop at any given time, even if there was no touch event.
Edit: Maybe I should use an NSMutableArray to store references to the Sprite objects and check the property, and remove the object, afterwards releasing it... This code works if there's one sprite on screen:
- (void)checkIfOut:(ccTime)dt {
for(Bullet *b in bulletArray){
if(b.outOfScreen){
[bulletArray removeObject:b];
[self removeChild:b cleanup:YES];
}
}
}
The problem seems to be in the [self removechild...]; call, it says the NSCFArray was being mutated while being enumrated...
Anyone?