Search code examples
objective-carraysnsexceptionarc4random

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:

//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.