本文介绍了在subarrayWithRange中防止NSRangeException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码,它允许我传入索引,并有选择地检索数组中的一些图像一定的范围长度 - 取决于方向。
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.
当在纵向时,范围应该是每个索引20个项目,并且我总共有43个项目。但是当我传入最后一个索引时,我得到超出[0..42]范围的索引59超出范围的异常。
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;
我如何防止这种情况?
谢谢。
推荐答案
if ((index * kItemsPerView + kItemsPerView) >= tempArray.count)
rangeForView = NSMakeRange( index * kItemsPerView, tempArray.count-index*kItemsPerView );
这篇关于在subarrayWithRange中防止NSRangeException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!