在我的项目中,我有一系列图像。图像显示在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的声明,但是我想它是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]];
}

08-26 14:22