i\'m trying to get the values of an array randomly but i\'m getting an error here is my code so far:
NSMutableArray *validMoves = [[NSMutableArray alloc] ini
The error you're getting (an arithmetic exception) is because validMoves
is empty and this leads to a division by zero when you perform the modulus operation.
You have to explicitly check for the case of an empty validMoves
array.
Also you should use arc4random_uniform
for avoiding modulo bias.
if (validMoves.count > 0) {
NSInteger pick = arc4random_uniform(validMoves.count);
[self movePiece:(TileClass *)[validMoves objectAtIndex:pick] withAnimation:NO];
} else {
// no valid moves, do something reasonable here...
}
As a final remark not that arc4random_uniform(0)
returns 0
, therefore such case should be avoided or you'll be trying to access the first element of an empty array, which of course will crash your application.