EXC_ARITHMETIC when accessing random elements of NSArray

后端 未结 1 435
一整个雨季
一整个雨季 2021-01-17 22:06

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         


        
相关标签:
1条回答
  • 2021-01-17 22:22

    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.

    0 讨论(0)
提交回复
热议问题