Casting an int to a string and outputting the value to a label

Discussion in 'iOS Programming' started by philwa2, Jul 30, 2008.

  1. macrumors newbie

    Jul 12, 2008

    Im trying to cast an int into a string so that I can output the value to the text property of a label - the code below generates a random number and assigns the value to the variable "generated" I then want to take this value convert it to a string and assign it the text of the label.

    Does anyone know how to do this?

    - (IBAction)clearText {
    int generated;
    generated = (random() % 100) + 1;
    mainText.text = generated;
  2. macrumors member

    Jul 9, 2008


    label.text = [NSString stringWithFormat:mad:"%d", generated];

    stringWithFormat works like printf in c. You can pass various formats to control the output and you can have multiple replacement values in the format string. For example,

    [NSString stringWithFormat:mad:"You have clicked %d out of %d buttons or %1.2f%%", var1, var2, (double)var1/(double)var2];

    might yield, "You have clicked 4 out of 5 buttons or 80.00%"
  3. macrumors 68000


    Nov 3, 2007
    to put it in the label use the following code
    labelName.text = [[NSNumber numberWithInt:variable] stringValue];

Share This Page