View Full Version : Casting an int to a string and outputting the value to a label

Jul 30, 2008, 04:46 PM

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;

Jul 30, 2008, 04:55 PM

label.text = [NSString stringWithFormat:@"%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:@"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%"

Jul 30, 2008, 04:55 PM
to put it in the label use the following code
labelName.text = [[NSNumber numberWithInt:variable] stringValue];