Search code examples
ioscocoa-touchnsarray

Split an NSArray into a fixed size and the rest


I have an NSArray in my project which has nearly 12 elements. I want to split this array into 2 arrays. I want the first 3 elements in the first array and the rest of the elements in the second NSArray.


Solution

  • Based on the answer of Alex Reynolds:

    You should make a range that has the length of 3 and make the first half of the array with it, then modify its location and length and create the second half of the array.

    NSArray *firstThreeArray;
    NSArray *otherArray;
    NSRange threeRange;
    
    threeRange.location = 0;
    threeRange.length = 3;
    
    firstThreeArray = [wholeArray subarrayWithRange:threeRange];
    
    threeRange.location = threeRange.length;
    threeRange.length = [wholeArray count] - threeRange.length;
    
    otherArray = [wholeArray subarrayWithRange:threeRange];