How to generate a random number in iOS

We can use the C function rand() for this:

int i = rand()%10+1;
NSLog(@"Random Number: %i", i);

This generates an integer between 1 and 10. Alternatively you can use the arc4random function:

int i = arc4random() % 10;
NSLog(@"Random Number: %i", i);

This will generate a random number between 0 and 9.

One thing of note is that often this function will generate the same number multiple times in a row which may not be what you want.

If you search the Xcode documentation you’ll also find a link to Apple’s Randomization Services. Read it and weep here: http://developer.apple.com/library/ios/#documentation/Security/Reference/RandomizationReference/Reference/reference.html.





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.