As of iOS 9 and OS X 10.11, you can use the new GameplayKit classes to generate random numbers in a variety of ways.
You have four source types to choose from: a general random source (unnamed, down to the system to choose what it does), linear congruential, ARC4 and Mersenne Twister. These can generate random ints, floats and bools.
At the simplest level, you can generate a random number from the system's built-in random source like this:
NSInteger rand = [[GKRandomSource sharedRandom] nextInt];
That generates a number between -2,147,483,648 and 2,147,483,647. If you want a number between 0 and an upper bound (exclusive) you'd use this:
NSInteger rand6 = [[GKRandomSource sharedRandom] nextIntWithUpperBound:6];
GameplayKit has some convenience constructors built in to work with dice. For example, you can roll a six-sided die like this:
GKRandomDistribution *d6 = [GKRandomDistribution d6];
[d6 nextInt];
Plus you can shape the random distribution by using things like GKShuffledDistribution
.
arc4random_uniform(x)
as described below by @yood. It is also in stdlib.h (after OS X 10.7 and iOS 4.3) and gives a more uniform distribution of the random numbers. Usageint r = arc4random_uniform(74);
– Stumble