防止 subarrayWithRange 中出现 NSRangeException

发布于 2024-10-04 16:09:43 字数 700 浏览 0 评论 0原文

我有这段代码,它允许我传入一个索引,并有选择地检索数组中一定范围长度的多个图像 - 取决于方向。

当处于纵向时,范围应该是每个索引 20 个项目,我总共有 43 个项目。但是,当我传入最后一个索引时,我收到索引 59 超出 [0..42] 范围的异常。

NSArray *tempArray = [self imageData];

UIDeviceOrientation devOr = [[UIDevice currentDevice] orientation];

int kItemsPerView;

if (UIDeviceOrientationIsPortrait(devOr)) {
    kItemsPerView = 20;
}else {
    kItemsPerView = 14;
}

NSRange rangeForView = NSMakeRange( index * kItemsPerView, kItemsPerView ); 

NSArray *subArray = [[tempArray subarrayWithRange:rangeForView] retain];
NSMutableArray *imagesForView = [NSMutableArray arrayWithArray:subArray];
[subArray release];

return imagesForView;

我怎样才能防止这种情况?

谢谢。

I have this code which allows me to pass in an index, and selectively retrieve, a number of images in an array for a certain range length - depending on orientation.

When in portrait the range should be be 20 items per index, and i have 43 items altogether. However when i pass in the last index, i get an out of range exception for index 59 beyond bounds of [0..42].

NSArray *tempArray = [self imageData];

UIDeviceOrientation devOr = [[UIDevice currentDevice] orientation];

int kItemsPerView;

if (UIDeviceOrientationIsPortrait(devOr)) {
    kItemsPerView = 20;
}else {
    kItemsPerView = 14;
}

NSRange rangeForView = NSMakeRange( index * kItemsPerView, kItemsPerView ); 

NSArray *subArray = [[tempArray subarrayWithRange:rangeForView] retain];
NSMutableArray *imagesForView = [NSMutableArray arrayWithArray:subArray];
[subArray release];

return imagesForView;

How can i prevent this?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

以为你会在 2024-10-11 16:09:43
if ((index * kItemsPerView + kItemsPerView) >= tempArray.count)
     rangeForView = NSMakeRange( index * kItemsPerView, tempArray.count-index*kItemsPerView );
if ((index * kItemsPerView + kItemsPerView) >= tempArray.count)
     rangeForView = NSMakeRange( index * kItemsPerView, tempArray.count-index*kItemsPerView );
哆啦不做梦 2024-10-11 16:09:43

另一种方法,只需使用 MIN() 函数来确定范围的结尾。

例子:

NSRange range;
range.location = index * kItemsPerView;
range.length = MIN(kItemsPerView, tempArray.count - range.location);
NSArray *imagesForView = [tempArray subarrayWithRange:range];

Alternate approach, just use MIN() function for determining the end of the range.

Example:

NSRange range;
range.location = index * kItemsPerView;
range.length = MIN(kItemsPerView, tempArray.count - range.location);
NSArray *imagesForView = [tempArray subarrayWithRange:range];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文