Search code examples
iosobjective-crandomarc4random

arc4random: limit the value of the random number generated


Built an iPhone app that generates a random number to a label when a button is pressed.

It works fine, but any value I put doesn't seem to limit the value of the random number generated. it's always 9 digits.

-(IBAction)genRandnum:(id)sender {

    NSNumber *randomNumber = [NSNumber numberWithInt: (arc4random() % 5) + 1];

    NSNumber *randomLabeltxt = [[NSString alloc] initWithFormat:@"It worked!", randomNumber];
    randLabel.text = [NSString stringWithFormat: @"%d", randomLabeltxt];
    [randomLabeltxt release];
}

As you can see, I've put 5 in after the % sign, but it generates 9 digit numbers.


Solution

    1. NSNumber is an Objective-C object, therefore you should use %@ to display it. %d shows a 9 digit number as that's the address of that NSNumber.

    2. NSString is not the same as an NSNumber.

    The correct and simplified code should look like:

    int randomNumber = (arc4random() % 5) + 1;
    // no need to create an NSNumber if you do not need to store it into an NS container.
    
    randLabel.text = [NSString stringWithFormat:@"It worked! %d", randomNumber];
    // no need to create an intermediate NSString variable.
    //  you can directly assign the string to the label's text.