Search code examples
iphoneobjective-cxcodeios4

Defining an index for an image array in Objective C


I've been trying to figure out how to have a UIImageView with a next and previous button which when clicked will go to the next or previous image in the array. So far, here's what I have.

In my .h file I have declared:

IBOutlet UIImageView *imageView;
NSArray *imageArray;

And I also added:

-(IBAction) next;

In the .m file I have:

-(void) viewDidLoad;
{
    imageArray = [[NSArray arrayWithObjects: 
                [UIImage imageNamed:@"1.png"], 
                  [UIImage imageNamed:@"2.png"], 
                  nil] retain];
}

Now here is where I'm struggling. I have the IBAction defined as follows in my .m:

-(IBAction)next 
{
     if (currentImage + 1 == [imageArray count])
     {
         currentImage = 0;
     }
     UIImage *img = [imageArray objectAtIndex:currentImage];
     [imageView setImage:img]; 
     currentImage++;
}

My problem is that I do not know where to define the currentImage index integer or how to define it. Is it in the header? The implementation? And how exactly do I declare it?

To be honest I'm not even 100% sure the code I currently have is right, although I think if I can define the index, it will work.

Any advice?


Solution

  • you need to declare the currentindex in the header like so:

    NSInteger currentImage;
    

    This way the value is saved throughout the views lifetime