好的,我使用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函数有什么问题吗?任何帮助都将不胜感激
发布于 2011-10-16 07:04:34
arc4random返回0或ray.count的偶数倍数。所以当你用ray.count修改它的时候,你得到0。然后从其中减去1,得到-1,这将转换为一个非常大的无符号整数。
发布于 2011-10-16 07:15:42
您还可以使用arc4random_uniform(upper_bound)函数生成一个范围内的随机数。下面将生成一个介于0和73之间(包括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.发布于 2011-10-16 07:10:21
问题是,因为您的pic-1构造偶尔会生成-1 (即未签名形式的4294967295 )。你需要去掉pic-1,简单地使用pic。
https://stackoverflow.com/questions/7781220
复制相似问题