Prevent NSRangeException in subarrayWithRange

2020-04-08 12:16发布

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.

2条回答
Fickle 薄情
2楼-- · 2020-04-08 12:43
if ((index * kItemsPerView + kItemsPerView) >= tempArray.count)
     rangeForView = NSMakeRange( index * kItemsPerView, tempArray.count-index*kItemsPerView );
查看更多
做个烂人
3楼-- · 2020-04-08 12:47

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];
查看更多
登录 后发表回答