NSRangeException and arc4random
-
10-02-2021 - |
Question
Alright, so I'm using arc4random to get a random image out of an array, the code for this is as follows:
//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? Any help would be greatly appreciated
Solution
arc4random is returning either 0 or an even multiple of 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.
OTHER TIPS
You can also use the arc4random_uniform(upper_bound)
function to generate a random number within a range. The following will generate a number between 0 and 73 inclusive.
arc4random_uniform(74)
arc4random_uniform(upper_bound) avoids modulo bias as described in the man page:
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.
The problem is that because your pic-1 construction generates -1 once for a while (which is 4294967295 in unsigned form). You need to get rid of pic-1 and simply use pic instead.