Ethan Allen Ethan Allen - 9 months ago 58
iOS Question

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

I have an

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


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 Source

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);