Take the 2-minute tour ×

I have a set of images named 0.png, 1.png, 2.png, etc...

Say I only have five. I want to use an integer variable (infoInt) to determine what image is displayed. Since I'm naming the images in numbers, I though I could define the image as what ever the integer was. i.e. infoInt.png (as infoInt changes). I'm not sure how I can approach it. Here is my attempt.

- (void)viewDidLoad{

[super viewDidLoad];
UIImage *img;

for (infoInt =0; infoInt<=5; infoInt++) {
    img = [UIImage imageNamed:infoInt".png"]; //What to do here? How do I use infoInt variable in image name?
    [imageView setImage:img];
share|improve this question

4 Answers 4

You can use +[NSString stringWithFormat:] to construct the name, as in

img = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png", infoInt]];
share|improve this answer
Hey thanks, the code definitely makes sense. But all the images seem to be displaying the one image, where infoInt = 5. I was hoping it was going to assign an integer for each increment. Is there a way I can increment the integer after assigning infoInt to an image. –  Adrian Farfan Jan 9 '13 at 8:47
@AdrianFarfan: You're assigning all the images, in turn, to the same imageview. Of course it's going to end up only displaying the last one. –  Kevin Ballard Jan 9 '13 at 19:03

Change this line

img = [UIImage imageNamed:infoInt".png"];



Hope it helps you

share|improve this answer

You can use stringWithFormat and use the for loop counter to generate image name as

share|improve this answer


NSString *fileName = [NSString stringWithFormat:@"%d.png", infoInt]
img = [UIImage imageNamed:fileName];

Also refer NSString Class Reference for more string functions.

share|improve this answer

Your Answer


