Search code examples
iosobjective-cprojectionnsset

Projection of properties of objects in NSArray/NSSet collections


I have an array of objects that I convert to a NSSet:

NSArray *arr = @[@{ @"someProp": @21, @"unnecessaryProp": @"tada" }, ... ];
NSSet *collection = [NSSet setWithArray:arr];

I would like to project the properties I want (by key) out of each object in the set and end up with a new array like:

NSArray *projectedArray = [collection allObjects]; // @[@{ "someProp": @21 }, ... ], "unnecessaryProp" has been removed

Besides enumeration, is there any other way, perhaps NSPredicate?

NOTE: The objects in the array are subclasses of NSObject, in my example I mentioned a NSDictionary


Solution

  • Since NSPredicate does not do projections, you would end up enumerating the set. I would enumerate it with a block, and project the keys in the individual dictionaries like this:

    NSArray *keep= @["someProp"];
    NSMutableArray *res = [NSMutableArray array];
    [collection enumerateObjectsUsingBlock:^(id dict, BOOL *stop) {
        NSArray *values = [dict objectsForKeys:keep notFoundMarker:@""];
        [res addObject:[NSDictionary dictionaryWithObjects:values forKeys:keep]];
    }];
    

    EDIT : (in response to comments)

    I should have mentioned that the objects inside the array are subclasses of NSObject and objectsForKeys is not a method.

    Then you could use MartinR's suggestion to build a dictionary using KVC:

    NSArray *keep= @["someProp"];
    NSMutableArray *res = [NSMutableArray array];
    [collection enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
        [res addObject:[obj dictionaryWithValuesForKeys:keep]];
    }];