user21293
user21293

Reputation: 6479

How do I generate random numbers on iOS?

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

Answers (6)

Himanshu padia
Himanshu padia

Reputation: 7730

Simple function for random number generation:

int r = arc4random() % 42;  // generate number up to 42 (limit)

Upvotes: 2

newtonapple
newtonapple

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

Andy Jacobs
Andy Jacobs

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

user23743
user23743

Reputation:

How random do you need? If you want random enough for crypto, then use SecRandomCopyBytes().

Upvotes: 7

Niyaz
Niyaz

Reputation: 54823

You should seed the random number generator with the current time.

srand(time(0));

Upvotes: 10

vava
vava

Reputation: 25421

Call srand() at the start of your program, it'll reseed random number generator

Upvotes: 3

Related Questions