0

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.

jscs
  • 63,694
  • 13
  • 151
  • 195
Abhinandan Pratap
  • 2,142
  • 1
  • 18
  • 39

2 Answers2

1

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];
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
0

As a category of NSArray :

@implementation NSArray (NSArray_Slicing)

- (NSArray *)subarraysFromIndex:(int)index {
    return @[[self sliceToIndex:index], [self sliceFromIndex:index]];
}


- (NSArray *)sliceFromIndex:(int)index {
    NSMutableArray*mutArray = [self mutableCopy];
    NSRange range = NSMakeRange(index, self.count - index);
    return [mutArray subarrayWithRange:range];
}


- (NSArray *)sliceToIndex:(int)index {
    NSMutableArray*mutArray = [self mutableCopy];
    NSRange range = NSMakeRange(0, index);
    return [mutArray subarrayWithRange:range];
}

@end

And then to call it:

NSArray *array = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12];
NSLog(@"First three: %@", [array sliceToIndex:3]);
NSLog(@"Remaining:   %@", [array sliceFromIndex:3]);
NSLog(@"Sliced:      %@", [array subarraysFromIndex:3]);
NSLog(@"Original:    %@", array);
Alex Chase
  • 960
  • 1
  • 7
  • 11
  • No need for making extra copies. `subarrayWithRange:` already creates and returns a new array. – jscs Sep 13 '17 at 13:32
  • 1
    Not necessary for demonstration purposes, but I would want to add some range checking to these methods to avoid exceptions. – jscs Sep 13 '17 at 13:34