3

Here is how i'm creating the int:

int randNumber = rand() % 4;
NSLog(@"%d", randNumber);

However every time I launch the app the number is the same, no matter what.

I created a button and attached an action to it that re-initializes the random number and logs the new number out and then it generates a random number, but on App launch the random number is always the same (i've launched it over 20 times).

Any idea why on app launch the random number is always the same?

Talon
  • 4,937
  • 10
  • 43
  • 57

4 Answers4

13

Try using arc4random(), which doesn't require a seed

Abby
  • 458
  • 2
  • 9
3

You need to specify a different seed every time your run the program. Given a seed, the random number generator generates a set of numbers. The same seed will produce the same set of numbers. To get a different set, you need a different seed.

Take a look at this for some guidance: Generating random numbers in Objective-C

Community
  • 1
  • 1
Oleksi
  • 12,947
  • 4
  • 56
  • 80
1

rand() is a pseudo random number generator. it uses a seed and produce the exactly sequence for each seed.

If you do this in the begin of the program

srand(time(NULL));

Will works

Tiago Peczenyj
  • 4,387
  • 2
  • 22
  • 35
0

You have to call srand(unsigned int seed); to seed the rand function. If you don't call srand it will be seeded with 1 every time.

dj2
  • 9,534
  • 4
  • 29
  • 52