views:

25

answers:

1

How can I combine multiple NSArrays into one array with alternating values? For example.

Array One: Orange, Apple, Pear

Array Two: Tree, Shrub, Flower

Array Three: Blue, Green, Yellow

The final array would need to be: Orange, Tree, Blue, Apple, Shrub, Green, etc

+3  A: 

Assuming the arrays are all of the same length:

NSUInteger numberOfArrays = 3;
NSUInteger arrayLength = [arrayOne length];
NSMutableArray *finalMutableArray = [NSMutableArray arrayWithCapacity:(arrayLength * numberOfArrays)];
for (NSUInteger index = 0; index < arrayLength; index++) {
    [finalMutableArray addObject:[arrayOne objectAtIndex:index]];
    [finalMutableArray addObject:[arrayTwo objectAtIndex:index]];
    [finalMutableArray addObject:[arrayThree objectAtIndex:index]];
}
NSArray *finalArray = [NSArray arrayWithArray:finalMutableArray];

You will probably want to test that the arrays are of the same length. You cannot add nil to an NSMutableArray or NSArray. You can add an NSNull placeholder, but it's probably better to check your input.

Alex Reynolds
Thanks! Thats super simple, can't believe I didn't think to do that. Note to self: get more sleep. :)
Brandon Schlenker
I added a fix to the capacity value.
Alex Reynolds