This is the simplest solution I could come up with:
id object = array.count == 0 ? nil : array[arc4random_uniform(array.count)];
You need to check count because it is not nil , but an empty NSArray will return 0 for count , and arc4random_uniform(0) return 0 . Therefore, without checking, you will go beyond the array.
This solution is tempting, but incorrect , because it will crash with an empty array:
id object = array[arc4random_uniform(array.count)];
For reference: documentation :
u_int32_t arc4random_uniform(u_int32_t upper_bound); arc4random_uniform() will return a uniformly distributed random number less than upper_bound.
The man page does not mention that arc4random_uniform returns 0 when 0 is passed as upper_bound .
In addition, arc4random_uniform is defined in <stdlib.h> , but the addition of #import not necessary in my iOS test program.
funroll Nov 13 '13 at 15:11 2013-11-13 15:11
source share