Reputation: 6479
What is the best way to generate random numbers using Objective-C on iOS?
If I use (int)((double) rand() / ((double)(RAND_MAX) + (double) 1) * 5.0)
to generate a number from 0 to 4, every time I start the program on the iPhone it generates the same numbers to start off with.
Upvotes: 22
Views: 52792
Reputation: 7730
Simple function for random number generation:
int r = arc4random() % 42; // generate number up to 42 (limit)
Upvotes: 2
Reputation: 4133
There is a very similar question here on StackOverFlow. Here is one of the better solutions (no need for seeding):
int r = arc4random() % 5;
Upvotes: 71
Reputation: 15245
i use
#define RANDOM_SEED() srandom(time(NULL))
#define RANDOM_INT(__MIN__, __MAX__) ((__MIN__) + random() % ((__MAX__+1) - (__MIN__)))
so you can give a min and max
Upvotes: 15
Reputation:
How random do you need? If you want random enough for crypto, then use SecRandomCopyBytes().
Upvotes: 7
Reputation: 54823
You should seed the random number generator with the current time.
srand(time(0));
Upvotes: 10
Reputation: 25421
Call srand()
at the start of your program, it'll reseed random number generator
Upvotes: 3