Ethan Allen Ethan Allen - 19 days ago 5
iOS Question

How to split NSArray into multiple different arrays based on an NSArray of indexes?

I have an

NSArray
that needs to be split into multiple arrays. I need to split them based on indexes I have in a separate
NSArray
array. So for example, my index array
*arrayIndexes
looks like this:

6
8
20
45


These are the indexes I need to split my single array on. Is there a simple/quick way to do this with Objective-C?

Answer

You can use subarrayWithRange: go get it done, below is an example

NSArray *arr = [NSArray arrayWithObjects:@"Temp1",@"Temp2",@"Temp3",@"Temp4",@"Temp5",@"Temp6",@"Temp7",@"Temp8",@"Temp9",@"Temp10",@"Temp11",@"Temp12",@"Temp13",@"Temp14",@"Temp15",@"Temp16",@"Temp17",@"Temp18", nil];
NSArray *arrIndex = [NSArray arrayWithObjects:@"4",@"10",@"12",@"14", nil];
NSMutableArray *arrTemp = [NSMutableArray new];
for  (int i=0;i<arrIndex.count;i++) {
    if (arrIndex.count == i+1) {
        [arrTemp addObject:[arr subarrayWithRange:NSMakeRange([arrIndex[i-1] intValue], arr.count - [arrIndex[i-1] intValue])]];
    } else if (i==0) {
        [arrTemp addObject:[arr subarrayWithRange:NSMakeRange(0, [arrIndex[i] intValue])]];
    }else {
        [arrTemp addObject:[arr subarrayWithRange:NSMakeRange([arrIndex[i-1] intValue],[arrIndex[i] intValue]-[arrIndex[i-1] intValue])]];
    }
}
for (NSArray *arr in arrTemp) {
    NSLog(@"Arra - %@",arr);
}