Reputation: 18670
So suppose I have an NSArray
populated with hundreds of NSDictionary
objects.
All dictionary objects have a value for the key name
but these values names may appear more than once in different objects.
I need to be able to filter this NSArray to only return one object per unique name
attribute (whichever object, first or last, I don't care).
This is how far I've got but obviously my filtered
array contains all objects rather than only unique ones.
I'm thinking there must be a way to tell the predicate to limit its results to only one / first match?
NSArray *allObjects = ... // This is my array of NSDictionaries
NSArray *uniqueNames = [allObjects valueForKeyPath:@"@distinctUnionOfObjects.name"];
NSArray *filtered = [allObjects filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(self.name IN %@)", uniqueNames]];
Thanks!
Upvotes: 1
Views: 1334
Reputation: 3327
NSMutableDictionary *uniqueObjects = [NSMutableDictionary dictionaryWithCapacity:allObjects.count];
for (NSDictionary *object in allObjects) {
[uniqueObjects setObject:object forKey:object[@"name"]];
}
Upvotes: 5