Prevent NSRangeException in subarrayWithRange

2020-04-08 12:56发布

问题:

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.

回答1:

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


回答2:

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