Very short snippet: iPhone, random numbers

If you need to generate random numbers in an application must set aside Apple iPhone Objective-C, because it does not propose any class order. The solution is proposed that the C: rand(), srand(), random(), srandom() e arc4random() .
Among the most popular is definitely arc4random() , because it does not require any special initialization or seeding functions, returning a good value "random", we could say that it is self-inizializzante.

1
2
3
4
5
/ / Generate a random number from 0 to 99
arc4random ( ) % 100 ; int rnd = arc4random ()% 100;

/ / Generate a random number from 20 to 70 (thx Luke)
( arc4random ( ) % 51 ) + 20 ; int rnd = (arc4random ()% 51) + 20;

2 comments: "Very short snippet: iPhone, random numbers"

  1. August 1, 2010 Luke:

    First of all, thanks ... I found many useful information in this blog, I just iphone developer to (time lost) ...
    Do not want to sound picky, and I have not even tried it on xcode, but I think there is an error in line 4 the comment .. I think that generated numbers go from 20 to 70 ...

    anyway thank you very much for what you do.

    Keep it up!

  2. August 1, 2010 Giovambattista Fazioli :

    @ Luke: you're not picky, indeed. It is a mistake, which I correct immediately. In the tests I had done wrong I copied a line that had to be so (to show how to set a range):

    1
    ( arc4random ( ) % 31 ) + 20 ; int rnd = (arc4random ()% 31) + 20;

    Which corresponds to the comment :) Thank you for everything, for the compliments and the error correction ... (they were all so attentive as you) :)

Leave a comment

XHTML TAG PERMIT: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERTION CODE:
 <pre></pre> // blocco generico <code></code> // blocco generico [cc_actionscript][/cc_actionscript] // Actionscript [cc_actionscript3][/cc_actionscript3] // Actionscript 3 [cc_css][/cc_css] // CSS Style Sheet [cc_html][/cc_html] // HTML [cc_js][/cc_js] // Javascript [cc_objc][/cc_objc] // Objective-C [cc_php][/cc_objc] // PHP [cc_sql][/cc_sql] // SQL