8

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

}
Cœur
  • 37,241
  • 25
  • 195
  • 267
NextRev
  • 1,711
  • 4
  • 22
  • 31

6 Answers6

27

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.

willcodejavaforfood
  • 43,223
  • 17
  • 81
  • 111
14

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
}
rougeExciter
  • 7,435
  • 2
  • 21
  • 17
  • Better yet, use a proper algorithm for generating random numbers between 0 and *n* from a uniform distribution of random numbers between 0 and *n_max*: The one implemented in java.util.Random#nextInt(int) is pretty well thought-out: http://java.sun.com/javase/6/docs/api/java/util/Random.html#nextInt%28int%29 – Joey Feb 18 '10 at 01:54
4

As obj-c is a superset of c language you can freely use rand function

Vladimir
  • 170,431
  • 36
  • 387
  • 313
2

If you need a cryptographically secure random number you may use:

int SecRandomCopyBytes (
   SecRandomRef rnd,
   size_t count,
   uint8_t *bytes
);

as described here.

jessecurry
  • 22,068
  • 8
  • 52
  • 44
1

I have had good success with arc4random() - just modulus it to set a range. For instance:

arc4random() % 100;

I would actively avoid using rand() as it does not produce truly random numbers and it needs to be seeded.

Brian Teeter
  • 844
  • 1
  • 8
  • 17
0
NSArray *arr=[NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil];
    NSMutableArray *valueArray=[[NSMutableArray alloc]init];
    int  count=0;
    while(count<5)
    {
        int rand= arc4random()%10;
        NSLog(@"%d",rand);

        NSString *str=[arr objectAtIndex:rand];
        if(![valueArray containsObject:str])
        {
        [valueArray addObject:str];
         count++;
        } 
    }
    NSLog(@"%@",valueArray);
Sishu
  • 1,510
  • 1
  • 21
  • 48