NSRangeException和arc4random

时间:2011-10-15 22:58:57

标签: objective-c arrays nsexception arc4random

好吧,所以我使用arc4random从数组中获取一个随机图像,其代码如下:

//ray is the array that stores my images
int pic = arc4random() % ray.count; 
tileImageView.image = [ray objectAtIndex:pic-1];
NSLog(@"Index of used image: %d", pic-1);

我多次调用此代码并且它有效一段时间但是经过一段时间后它总是因为这个错误而崩溃:

 *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** - [__NSArrayM objectAtIndex:]: index 4294967295 beyond bounds [0 .. 39]'

我的问题是,为什么这个荒谬的大数字被创造了? arc4random函数有问题吗?任何帮助将不胜感激

3 个答案:

答案 0 :(得分:2)

您还可以使用arc4random_uniform(upper_bound)函数生成范围内的随机数。以下将生成0到73之间的数字。

arc4random_uniform(74)

arc4random_uniform(upper_bound)避免了模页偏差,如手册页所述:

arc4random_uniform() will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.

答案 1 :(得分:0)

arc4random返回0或甚至是ray.count的倍数。因此,当你通过ray.count来修改它时,你得到0.然后从中减去1,得到-1,这转换为一个非常大的无符号整数。

答案 2 :(得分:0)

问题是因为你的pic-1构造暂时产生-1(无符号形式为4294967295)。你需要摆脱pic-1而只需使用pic。