Search code examples
objective-cfor-loopios4nsarrayrange

Extract a range from NSArray


I need to display 6 views and each view should display 20 items (UIButtons). I have one big NSArray which contains the items for all 6 views.

For example, view 1 should be items 0-19, view 2 should be items 20-39.

How would i extract the relevant range out of the array? Maybe using NSRange with a length of 20, but the start location would need to change for each view... without a switch statement ideally :)

Thanks


Solution

  •  static const NSUInteger ItemsPerView = 20;
     NSUInteger startIndex = viewIndex * ItemsPerView;
     NSUInteger count = MIN( completeArray.count - startIndex, ItemsPerView );
     NSArray *itemsForView = [completeArray subarrayWithRange: NSMakeRange( startIndex, count )];