views:

27

answers:

1
// Declare index in Header.h

index=0;

- (IBAction)next {
    index++;
    // Set imageCount to as many images as are available
    int imageCount=2;
    if (index<=imageCount) {
        NSString* imageName=[NSString stringWithFormat:@"img%i", index];
        [picture setImage: [UIImage imageNamed: imageName]];
    }
}

Where do I declare index in my header file and how?

+2  A: 

If index is used only within the -next method, you can define a static variable.

- (IBAction)next {
    static int index = 0;    // <-- here
    index++;
    // Set imageCount to as many images as are available
    int imageCount=2;
    if (index<=imageCount) {
        NSString* imageName=[NSString stringWithFormat:@"img%i", index];
        [picture setImage: [UIImage imageNamed: imageName]];
    }
}

Note that all instances will share the same index.

But I believe it's better to make index as an ivar, e.g.

@interface ... {
   ...
   int index;
   ...
}

it is automatically initialized to 0 when the instance is constructed, and methods other than next can use the index. Also, each instance will have its own index.

KennyTM
Ok the only problem I now have is that all my images (16) are called img01 img02 etc but none of my images are now displaying except first one how does this work?
Will
Ok now when I click next no image is displayed?
Will
@Will: You need `img%02d` instead of `img%i`.
KennyTM
Wait I have changed all of my images to img1 img2 and so on but it still won't display them except for the first one when I click next where the image should be just goes white :(
Will
Please help....
Will
@Will: Which iPhone OS version are you running on? You need the file extension i.e. `img%i.png` if you're targeting iPhone OS <4.
KennyTM