iOS - 将 arrayIndex 限制在 0 到 98 之间

iOS - limiting the arrayIndex between 0 and 98

在我的项目中,我有一组图像。图像显示在 imageView 上,我可以通过滑动在图像之间移动。但是当我归零并向左滑动时(又名前一张照片,它将 arrayIndex 减少一个)我得到一个错误(SIGABRT)。 这是我负责在图像之间移动的代码:

-(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]];
}

}

您永远不会修改 arrayIndex 包装盒。应该这样做:

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

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

}

由于arrayIndex是一个无符号整数,当arrayIndex为0并且你说:

arrayIndex--;

这会导致它环绕到一个非常大的数字,即 >= 0。您应该在递减它之前检查 arrayIndex 是否 > 0。例如,如果您希望图像换行:

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

您没有向我们展示 arrayIndex 的声明,但我猜它是 unsigned long,因为您用 %lu.

打印了它

考虑当 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]];

你需要检查 arrayIndex == 0 之前 你递减它,像这样:

-(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]];
}