Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number in iOS?

How do you generate a random number when a button is clicked, and depending on that number, different actions take place.

I probably only need a random number from 1-10.

-(IBAction)buttonClicked{

"generate the random number"

if(number == 1){

    something happens
}

else if(number == 2){
    something else happens
}

etc

}
like image 518
NextRev Avatar asked Feb 17 '10 15:02

NextRev


2 Answers

There are a few problems with rand() which there are loads of posts about and they recommend that you use arc4random() instead. This function is seeded automatically and has a 'better' algorithm for number generation.

int myNumber = arc4random() % 10

This would mean that myNumber would be between 0-9.

So in your case you want:

int number = (arc4random() % 2) + 1;

which would give you a range of 1-2.

like image 169
willcodejavaforfood Avatar answered Oct 21 '22 01:10

willcodejavaforfood


And please, please, if you are generating a random number from 1 to 10... use switch rather than a pile of if {} else if {} clauses:

switch (arc4random() % 10){
case 0:
   //blah blah
   break;
case 1:
   //blah blah
   break;
//etc etc
}
like image 31
rougeExciter Avatar answered Oct 21 '22 02:10

rougeExciter