开发者

Prevent NSRangeException in subarrayWithRange

I have this code which allows me to pa开发者_StackOverflowss 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.


if ((index * kItemsPerView + kItemsPerView) >= tempArray.count)
     rangeForView = NSMakeRange( index * kItemsPerView, tempArray.count-index*kItemsPerView );


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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜