If you need to generate a random number within your iPhone application, you have to push aside Objective-C, as there is not a class with a method for generating random numbers (as in Java). 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);
Comments
5 Responses to “Getting a Random Number”
Leave Comment
All Content Copyright © 2008-2012 • iOS Developer Tips, All Rights Reserved.
The freely available, and BSD licensed, Mersenne twister also works quite handsomely on the iPhone.
[Reply]
I tend to make a macro to do this:
#define RANDOM_INT(__MIN__, __MAX__) ((__MIN__) + arc4random() % ((__MAX__+1) – (__MIN__)))
[Reply]
Thank you!
[Reply]
thnaks… it helped..
[Reply]
thanks
[Reply]