NSRangeException和arc4random

问题描述:

好了,所以我用arc4random得到一个随机图像从一个数组,这样做的代码如下:NSRangeException和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函数有问题吗?任何帮助将不胜感激

arc4random返回0或ray.count的偶数倍。所以当你用ray.count对它进行修改时,你得到0.然后你从中减去1,得到-1,这意味着一个非常大的无符号整数。

+0

啊,非常感谢你!所以正确的做法是'int pic = arc4random()%(ray.count -1);',否? – kopproduction

+0

@kopproduction:如果你想从数组中返回一个随机项,你不需要减去任何东西。模数运算符已经确保该索引小于ray.count。 – Chuck

+0

好的,再次感谢,我不知道:) – kopproduction

问题是,因为你的pic-1结构会在一段时间内产生-1(这是4294967295的无符号形式)。你需要摆脱pic-1,而不是简单地使用pic。

您还可以使用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.