Home > DeveloperSection > Forums > Generating Random Numbers in Objective-C
Pooja Malohtra
Pooja Malohtra

Total Post:47

Posted on    August-17-2015 11:48 PM

 iPhone iPhone  Ios  Objective C 

 1 Reply(s)
 568  View(s)
Rate this:

I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method:


I'm not interested in a discussion about seeds or true randomness, just how you accomplish the same task in Objective-C. I've scoured The Google, and it just seems to be lots of different and conflicting bits of information.

Jessica James
Jessica James

Total Post:16

Posted on    August-18-2015 11:22 PM

Use the arc4random_uniform(upper_bound) function to generate a random number within a range. The following will generate a number between 0 and 73 inclusive.




arc4random_uniform(upper_bound) avoids modulo bias


arc4random_uniform() will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.

Modified On Mar-18-2016 11:21:30 PM

Don't want to miss updates? Please click the below button!

Follow MindStick