简体   繁体   English

NSRangeException和arc4random

[英]NSRangeException and arc4random

Alright, so I'm using arc4random to get a random image out of an array, the code for this is as follows: 好吧,所以我使用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);

I'm calling this code multiple times and it works for a while but after some time it always crashes because of this error: 我多次调用此代码并且它可以工作一段时间但是经过一段时间后它总是因为这个错误而崩溃:

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

My question is, why is this ridiculously large number created? 我的问题是,为什么这个荒谬的大数字被创造了? Is there something wrong with the arc4random function? arc4random函数有问题吗? Any help would be greatly appreciated 任何帮助将不胜感激

You can also use the arc4random_uniform(upper_bound) function to generate a random number within a range. 您还可以使用arc4random_uniform(upper_bound)函数生成范围内的随机数。 The following will generate a number between 0 and 73 inclusive. 以下将生成0到73之间的数字。

arc4random_uniform(74)

arc4random_uniform(upper_bound) avoids modulo bias as described in the man page: 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.

arc4random is returning either 0 or an even multiple of ray.count. arc4random返回0或甚至是ray.count的倍数。 So when you mod it by ray.count, you get 0. You then subtract 1 from this, getting -1, which translates to a very large unsigned integer. 因此,当您通过ray.count对其进行修改时,您得到0.然后从中减去1,得到-1,这将转换为非常大的无符号整数。

The problem is that because your pic-1 construction generates -1 once for a while (which is 4294967295 in unsigned form). 问题是因为你的pic-1构造暂时生成-1(无符号形式为4294967295)。 You need to get rid of pic-1 and simply use pic instead. 你需要摆脱pic-1而只是简单地使用pic。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM