Reputation: 9054
Is there a one-liner to do the following
NSMutableArray *allpoints = [[NSMutableArray alloc] init];
for (NSMutableArray *arr in self.points)
[allpoints addObjectsFromArray:arr];
I have an array of arrays (self.points
) and I am joining all of the objects in the subarrays into a single array.
Upvotes: 1
Views: 604
Reputation: 9382
There is not a way to add all objects in an array of arrays (e.g., every NSMutableArray
in self.points
to another array without iterating through.
However, you could add a category to NSArray
to do exactly what you're doing now, and then call it with one line later.
Upvotes: 1
Reputation: 321
NSArray *array1 = @[ @"a", @"b", @"c" ];
NSArray *array2 = @[ @"d", @"e", @"f" ];
NSArray *array3 = @[ array1, array2 ];
NSArray * flattenedArray = [array3 valueForKeyPath:@"@unionOfArrays.self"];
NSLog(@"flattenedArray: %@", flattenedArray);
Output:
flattenedArray: ( a, b, c, d, e, f )
Upvotes: 7
Reputation: 7310
I don't think there is a way to do this.
NSMutableArray *allpoints = [[NSMutableArray alloc] initWithArray:self.points]
would give you an array of the arrays, but there is no single line solution. I'd suggest writing a category that will do this for you so you can easily reuse it.
Upvotes: 0
Reputation: 3872
If you are initializing the array and adding objects at the same time then there is an initializer for that.
NSMutableArray *allpoints = [[NSMutableArray alloc] initWithArray:self.points];
If you already have the mutable array defined and you want to just append objects to the end then you can use the following.
[allpoints addObjectsFromArray:self.points];
Upvotes: 0