在我的项目中,我有一组图像。图像显示在 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
before 你递减它,像这样:
-(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]];
}
关于iOS - 将 arrayIndex 限制在 0 到 98 之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29478080/