Saturday, June 1, 2013

NSArray subarrayWithRange example in Objective C (iOS).


NSArray subarrayWithRange

Returns a new array containing the receiving array’s elements that fall within the limits specified by a given range.

- (NSArray *)subarrayWithRange:(NSRange)range

Parameters
range
A range within the receiving array’s range of elements.

Return Value
A new array containing the receiving array’s elements that fall within the limits specified by range.

Discussion of [NSArray subarrayWithRange]
If range isn’t within the receiving array’s range of elements, an NSRangeException is raised.

For example, the following code example creates an array containing the elements found in the first half of wholeArray (assuming wholeArray exists).

NSArray *halfArray;
NSRange theRange;

theRange.location = 0;
theRange.length = [wholeArray count] / 2;

halfArray = [wholeArray subarrayWithRange:theRange];

NSArray subarrayWithRange example.
NSUInteger size = 50;

for (NSUInteger i = 0; i * size < [testArray count]; i++) {
  NSUInteger start = i * size;
  NSRange range = NSMakeRange(start, MIN([testArray count] - start, size));
  [sortedArray addObject:[testArray subarrayWithRange:range]];
}

Example of [NSArray subarrayWithRange].
 static const int kItemsPerView = 20;
 NSRange rangeForView = NSMakeRange( viewIndex * kItemsPerView, kItemsPerView );
 NSArray *itemsForView = [completeArray subarrayWithRange: rangeForView];

NSArray subarrayWithRange example.
NSMutableArray *arrayOfArrays = [NSMutableArray array];

int itemsRemaining = [stuff count];
int j = 0;

while(j < [stuff count]) {
    NSRange range = NSMakeRange(j, MIN(30, itemsRemaining));
    NSArray *subarray = [stuff subarrayWithRange:range];
    [arrayOfArrays addObject:subarray];
    itemsRemaining-=range.length;
    j+=range.length;
}

End of NSArray subarrayWithRange example article.