3

I am having problem with using subArrayWithRange.

Basically, what I want to do is make subarray of 50 elements or less from mainArray for example if mainArray has 70 elements I want a sortedArray to have an array of first 50 elements in first index and another array of 20 elements in the last index of sortedArray

Hope I am clear what I want to do get.

anyway, my code is

for (int i=0; i<=ceilLoopCount; i++) {
    [sortedArray insertObject:[testArray subarrayWithRange:NSMakeRange(0,50)] atIndex:i]; 
} 

and the problem I am having is I only get the same 50 elements in all the array

Please help, Pondd

2 Answers 2

14
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]];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Thankz for help but I am getting Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSArray subarrayWithRange:]: index 449 beyond bounds [0 .. 433]' Not sure what you meant by "- loc"
0
            NSMutableArray *arrayOfArrays = [NSMutableArray array];
            int batchSize = 30;

            for(int j = 0; j < [stuff count]; j += batchSize) {

                NSArray *subarray = [stuff subarrayWithRange:NSMakeRange(j, MIN(batchSize, [stuff count] - j))];
                [arrayOfArrays addObject:subarray];
            }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.