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

标签 ios objective-c arrays indexing unsigned-integer

在我的项目中,我有一组图像。图像显示在 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/

相关文章:

ios - 是否可以拥有一个模板并根据页面控件中的数组计数添加一定数量的 View Controller ?

ios - 我如何创建一个 plist,我可以在我的应用程序中很好地访问 array -> dictionary -> dictionary -> array -> mYClassInstances in swift?

ios - 辛奇-shouldSendPushNotifications : called when recipient attempts to answer call from local notification

arrays - VBA - 在多维数组中分割 CSV 文件

java - 历史数组

ios - 从 App Delegate 推送 View Controller

ios - 使用容器自动布局

objective-c - iOS5下添加SplitViewController View 麻烦

ios - 在 Objective-C 中调试简单的函数

javascript - 根据 React 中的输入字段过滤对象数组