I have a “snake game” like player and I’m running into some problems when removing the end tail piece when the body reaches a certain length. Right now I have this:
if (i > maxHealth) {
id object = [tail objectAtIndex:i-maxHealth-1];
[tail removeObject:object];//This part doesn't work, if I comment this line out it works but the object is still in the array
[self.tileMap removeChild:object cleanup:YES];
}
Where i is the length of the “snake” when the scene is init i is equal to 0 and the player moves it adds the “tail” image to the scene and to a NSMutableArray called tail. I get this in the debugger:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM insertObject:atIndex:]: index 4 beyond bounds [0 .. 2]'
Which doesn’t make any sense to me because before I added the line to remove the sprite from the array and just use object to remove the sprite from the scene it worked fine.
You should learn how to work with breakpoints to identify the right place in your code, because clearly, your problem is not the line you think it is:
It basically tells you all there is to know: you are trying to insert an object at index 4 of an array that only has three indices (0,1,2).
So, your call to removeObject is not the reason for the exception you get, but the cause for this exception, happening later, when you try to insert an Object.
I guess the index is wrong, apparently, because you removed your object at index 3 or 4 in the step before but did not update the valid indices.
To fix these kinds of problems, I recommend to go to the Breakpoints Navigator in Xcode (cmd+6) and click the small bottem left “+” and “Add Exception Breakpoint” set to “all”. Run your code and the debugger will pop up right where the exception happens.