访问NSArray的随机元素时为EXC_ARITHMETIC [英] EXC_ARITHMETIC when accessing random elements of NSArray
问题描述
我正在尝试随机获取数组的值,但出现错误 到目前为止,这是我的代码:
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] init];
for (int i = 0; i < 100; i++){
[validMoves removeAllObjects];
for (TileClass *t in tiles ) {
if ([self blankTile:t] != 0) {
[validMoves addObject:t];
}
}
NSInteger pick = arc4random() % validMoves.count;
[self movePiece:(TileClass *)[validMoves objectAtIndex:pick] withAnimation:NO];
}
推荐答案
您收到的错误(算术异常)是因为validMoves
为空,并且在执行模数运算时导致被零除.
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.
您必须明确检查是否为空的validMoves
数组.
另外,您应该使用arc4random_uniform
以避免模偏差.
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...
}
最后一点不是arc4random_uniform(0)
返回0
,因此应避免这种情况,否则您将尝试访问空数组的第一个元素,这当然会使您的应用程序崩溃.
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.
这篇关于访问NSArray的随机元素时为EXC_ARITHMETIC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!