I have an NSArray of objects called MMPlace, which has NSArray of MMProduct objects.
How do I get a united NSArray of all MMProduct objects that my Array of MMPlace object contains? Something like NSArray *arr = [array valueForKeyPath:@"@unionOfObjects.products"];
would be nice, though this specific example doesn't work.
You can do this with @unionOfArrays
. The bit you were missing is that because the arrays are directly nested, the key on the right of the collection operator must be self
:
NSArray *nestedValues = @[@[@1, @2, @3], @[@4, @5, @6]]
NSArray *flattenedValues = [nestedValues valueForKeyPath:@"@unionOfArrays.self"];
// flattenedValues contains @[@1, @2, @3, @4, @5, @6]
Create an NSMutableArray, loop through your original array and call addObjectsFromArray:
with each subarray.
I don't think there is an off-the-shelf method that does what you need, but you can easily "flatten" your array in a for
loop, and hide the method in a category:
Edit: added a category.
@interface NSArray (flatten)
-(NSArray*) flattenArray;
@end
@implementation NSArray (flatten)
-(NSArray*) flattenArray {
// If inner array has N objects on average, multiply count by N
NSMutableArray *res = [NSMutableArray arrayWithCapacity:self.count];
for (NSArray *element in self) {
[res addObjectsFromArray:element];
}
return res;
}
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With