3

I have an NSArray of say 100 NSManagedObjects and I need to split that into an NSArray that contains 10 NSArray objects that each hold 10 of theses NSManagedObjects, how would I accomplish that?

I am going to do some paging and this will work well for me.

Manlio
  • 10,768
  • 9
  • 50
  • 79
Slee
  • 27,498
  • 52
  • 145
  • 243
  • 1
    Assuming you just would like to pass in an array and have the same code work every time, why not just pass it an NSRange of length 10 and position [whichever], along with the original unmodified NSArray, and have the code for a page work based on the NSRange, instead of absolute index? – Alex Gosselin Jul 29 '11 at 00:24
  • That sounds perfect - how do I accomplish that? – Slee Jul 29 '11 at 00:36
  • 4
    This is almost an exact duplicate of http://stackoverflow.com/questions/6852012/what-is-an-easy-way-to-break-an-nsarray-with-4000-objects-in-it-into-multiple-ar. The answer was to use `subArrayWithRange:` repeatedly, with a shifting range. – Rudy Velthuis Jul 29 '11 at 00:42

4 Answers4

5

How are you getting these NSManagedObjects? If you're using an NSFetchRequest, you may want to keep that around and only get 10 results at a time from it.

Joe Osborn
  • 1,145
  • 7
  • 10
3

Here is my code:

[object splitArrayWithArray:arrayWith100Objects rangeNumber:10];

- (NSArray*) splitArrayWithArray:(NSArray*)rawArray rangeNumber:(int)rangeNumber{
    int totalCount = rawArray.count;
    int currentIndex = 0;

    NSMutableArray* splitArray = [NSMutableArray array];

    while (currentIndex<totalCount) {
        NSRange range = NSMakeRange(currentIndex, MIN(rangeNumber, totalCount-currentIndex));
        NSArray* subArray = [rawArray subarrayWithRange:range];
        [splitArray addObject:subArray];
        currentIndex +=rangeNumber;
    }
    return splitArray;
}
Darren AY
  • 31
  • 1
2

Something along these lines should work instead of breaking it into separate arrays

//make a new range for each page
NSRange myRange = NSMakeRange(10, 10);
NSArray * myArray = [NSArray array];

//...pass both into a function
for (int i = myRange.location; i < myRange.location + myRange.length; i++) {
    //stuff with the array elements
    [[myArray objectAtIndex:i] doSomething];
}
Alex Gosselin
  • 2,942
  • 21
  • 37
1

It's no one-liner, but this will split an array into pages:

NSArray *arrayToSplit = ...

int pageSize = 50;
NSMutableArray *arrayOfPages = [NSMutableArray new];

NSRange range = NSMakeRange(0, pageSize);

while (range.location < arrayToSplit.count) {
    if (range.location + range.length >= arrayToSplit.count)
        range.length = arrayToSplit.count - range.location;

    [arrayOfPages addObject:[arrayToSplit objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:range]]];

    range.location += range.length;
}
nil
  • 1,192
  • 9
  • 12