Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray of united Arrays

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.

like image 869
Eugene Avatar asked Dec 20 '11 00:12

Eugene


3 Answers

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]
like image 134
Ben Lings Avatar answered Oct 24 '22 05:10

Ben Lings


Create an NSMutableArray, loop through your original array and call addObjectsFromArray: with each subarray.

like image 28
Chuck Avatar answered Oct 24 '22 04:10

Chuck


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
like image 26
Sergey Kalinichenko Avatar answered Oct 24 '22 05:10

Sergey Kalinichenko