views:

101

answers:

3

I have seen some examples of the random int in Objective-C, but all people are complaining about the same number sequence every time the application runs. I have read about seeding the random number, but I am not sure what that even means.

How can a random number be generated differently every time, even after application has relaunched?

Could some data be stored in NSUserDefaults and then, depending on that, different values get generated?

+3  A: 

You can seed your random with the following code:

srand([[NSDate date] timeIntervalSince1970]);

This will give you a new random sequence every time.

Martin Ingvar Kofoed Jensen
+1  A: 

I've been using arc4random, which you don't need to seed. You can give it a try.

pgb
+4  A: 

Here's a discussion on the Apple developer forums.

Use arc4random() instead of either random() or rand(). It used /dev/urandom and generates much better pseudo-random numbers. Both rand() and random() are basically bad random number generators.

See: man arc4random

#include <stdlib.h>
picknumber = arc4random() % 3 + 1; 
Robert Greiner
how can I get a random between 1 and 10 using arc4Random()?
alJaree
picknumber = arc4random() % 10 + 1;
drachenstern