Generating Random Numbers in Objective-C

Total Post:47

 1387  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.

  1. Post:16

    Re: Generating Random Numbers in Objective-C

    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 Apr-10-2018 02:16:15 AM



Enter your email address here always to be updated. We promise not to spam!