防止 subarrayWithRange 中出现 NSRangeException
我有这段代码,它允许我传入一个索引,并有选择地检索数组中一定范围长度的多个图像 - 取决于方向。
当处于纵向时,范围应该是每个索引 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一种方法,只需使用 MIN() 函数来确定范围的结尾。
例子:
Alternate approach, just use
MIN()
function for determining the end of the range.Example: