22

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
user21293
  • 6,439
  • 11
  • 44
  • 57

6 Answers6

71

There is a very similar question here on StackOverFlow. Here is one of the better solutions (no need for seeding):

int r = arc4random() % 5;
Community
  • 1
  • 1
newtonapple
  • 4,123
  • 3
  • 33
  • 31
15

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

Andy Jacobs
  • 15,187
  • 13
  • 60
  • 91
10

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

srand(time(0));
Niyaz
  • 53,943
  • 55
  • 151
  • 182
6

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

3

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

vava
  • 24,851
  • 11
  • 64
  • 79
2

Simple function for random number generation:

int r = arc4random() % 42;  // generate number up to 42 (limit)
Regexident
  • 29,441
  • 10
  • 93
  • 100
Himanshu padia
  • 7,428
  • 1
  • 47
  • 45
  • While being redundant as an answer, I like how the number 42 is being used instead of 5 here. – Toastor May 08 '13 at 14:28
  • 1
    As I want to generate random number up to 41 so I have given 42, so it will generate between 0 to 41 including 0 & 41, as I want to use 41. – Himanshu padia May 09 '13 at 05:13
  • Fair enough. However, you are strongly encouraged to read "The Hitchhikers Guide to the Galaxy" - I believe it is a non-optional reading for programmers in general. – Toastor May 10 '13 at 13:04
  • 1
    @Toastor: Too funny ;) – Jordan Jul 11 '14 at 13:27