Combining multiple NSArrays
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
[@[@[@1,@2],@[@3,@4],@[@5,@6]] valueForKeyPath:@"@unionOfArrays.self"]
So once you have a array of arrays you call unionOfArrays
collection operator.
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.
If you have array of arrays
NSArray *arrayOfArrays = ...;
NSMutableArray *oneArray = [NSMutableArray array];
for (NSArray *tmpArray in arrayOfArrays) {
[oneArray addObjectsFromArray:tmpArray];
}
精彩评论