How to generate a random number

If you need to generate a random number within your app, you have to push aside Objective-C, as there is no class with a built-in random number generator. The alternative is to use C, among the functions available are: rand(), srand(), random(), srandom() and arc4random().

arc4random() tends to be preferred as it does not require seeding, the function automatically initializes itself.

// Get random value between 0 and 99
int x = arc4random() % 100;
// Get random number between 500 and 1000
int y =  (arc4random() % 501) + 500;

Update: thanks Dave Verwer and Kevin Conner for pointing out the advantages of arc4random_uniform.

Apple docs:

arc4random_uniform() will return a uniformly distributed random number less than upper_bound.

  1. I tend to make a macro to do this:

    #define RANDOM_INT(__MIN__, __MAX__) ((__MIN__) + arc4random() % ((__MAX__+1) – (__MIN__)))

Comments are closed.