gpt4 book ai didi

ios - NSArray索引超出范围错误

转载 作者:行者123 更新时间:2023-12-01 17:54:16 25 4
gpt4 key购买 nike

我创建了一个具有两个按钮的简单图像浏览器,以查看下一个和上一个图像。

这是代码。

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (strong, nonatomic) NSArray *images;
@property (assign, nonatomic) NSInteger imageIndex;
@property (strong, nonatomic) UIBarButtonItem *nextButton;
@property (strong, nonatomic) UIBarButtonItem *prevButon;

@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];

// Adding Next and Previous buttons
self.nextButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"next"] style:UIBarButtonItemStylePlain target:self action:@selector(nextButtonPressed)];
self.prevButon = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"previous"] style:UIBarButtonItemStylePlain target:self action:@selector(previousButtonPressed)];

self.navigationItem.rightBarButtonItems = @[self.nextButton, self.prevButon];


// Loading images
self.images = @[
[UIImage imageNamed:@"1"],
[UIImage imageNamed:@"2"],
[UIImage imageNamed:@"3"],
[UIImage imageNamed:@"4"],
[UIImage imageNamed:@"5"],
[UIImage imageNamed:@"6"],
[UIImage imageNamed:@"7"],
[UIImage imageNamed:@"8"],
[UIImage imageNamed:@"9"]
];

self.imageIndex = 0;
self.imageView.image = self.images[self.imageIndex];
}

- (void)nextButtonPressed
{
self.imageIndex++;
self.imageView.image = self.images[self.imageIndex];
}

- (void)previousButtonPressed
{
self.imageIndex--;
self.imageView.image = self.images[self.imageIndex];
}

@end

我的问题是,如果我点击最后一个图像之后的下一个按钮或当第一个图像时单击上一个按钮,它将抛出超出范围错误的索引。

如何阻止这种情况的发生?

谢谢。

最佳答案

您必须检查索引中是否存在索引。
您可以使用nextButtonPressedpreviousButtonPressed方法进行验证:

- (void)nextButtonPressed
{
if (imageIndex < ([self.images count] - 1))
{
self.imageIndex++;
self.imageView.image = self.images[self.imageIndex];
}
}

- (void)previousButtonPressed
{
if (imageIndex >= 1)
{
self.imageIndex--;
self.imageView.image = self.images[self.imageIndex];
}
}

有关信息,如果索引超出数组末尾,则NSArray会引发 NSRangeException(请参阅 documentation)。

关于ios - NSArray索引超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21074267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com