views:

22

answers:

1

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

Simple, just to learn new skills.

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. What am doing wrong?

+4  A: 
  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.
KennyTM
Awesome, that fixed it. well explained too so i could see what went wrong. Thanks a bunch (: