Search code examples
iosobjective-carraysindexingunsigned-integer

iOS - limiting the arrayIndex between 0 and 98


in my project i have an array of images. The images are displayed on an imageView, i can move between the images with swipes. But when i get to zero and swipe left (aka previous photo, which decreases the arrayIndex by one) i get an error (SIGABRT). here's my code that's responsible for moving between images:

-(IBAction)nextPhoto:(id)sender{
arrayIndex++;
NSLog(@"rigth! at index %lu", arrayIndex);
if (arrayIndex <= 98){
displayImage.image = [UIImage imageNamed:[imageArray objectAtIndex:arrayIndex]];
} else {
    displayImage.image = [UIImage imageNamed:[imageArray objectAtIndex:0]];
}

}
-(IBAction)previousPhoto:(id)sender{
 arrayIndex--;
 NSLog(@"Left! at index %lu", arrayIndex);
 if (arrayIndex >= 0){
 displayImage.image = [UIImage imageNamed:[imageArray  objectAtIndex:arrayIndex]];
} else {
   displayImage.image = [UIImage imageNamed:[imageArray objectAtIndex:98]];
}

}

Solution

  • You didn't show us the declaration of arrayIndex, but I guess it's unsigned long, since you print it with %lu.

    Consider what happens when arrayIndex == 0:

    // arrayIndex == 0
    arrayIndex--;
    // Now arrayIndex == ULONG_MAX.
    // The following condition is always true for unsigned longs.
    if (arrayIndex >= 0){
        // This branch is always taken.
        // The following objectAtIndex: fails for ULONG_MAX.
        displayImage.image = [UIImage imageNamed:[imageArray  objectAtIndex:arrayIndex]];
    

    You need to check for arrayIndex == 0 before you decrement it, like this:

    -(IBAction)nextPhoto:(id)sender {
        ++arrayIndex;
        if (arrayIndex >= imageArray.count) {
            arrayIndex = 0;
        }
        displayImage.image = [UIImage imageNamed:imageArray[arrayIndex]];
    }
    
    -(IBAction)previousPhoto:(id)sender {
        if (arrayIndex == 0) {
            arrayIndex = imageArray.count - 1;
        } else {
            --arrayIndex;
        }
        displayImage.image = [UIImage imageNamed:imageArray[arrayIndex]];
    }