iOS engineer who likes clean, simple designs and sans-serif.


Collection Operators iOS7

Collection Operators allow actions to be performed on the items of a collection using key path notation and an action operator. If you know SQL, I like to think of these as “group by” operations.

For example:

NSNumber *transactionAverage = [transactions valueForKeyPath:@"@avg.amount"];
NSDate *latestDate = [transactions valueForKeyPath:@""];
NSDate *earliestDate = [transactions valueForKeyPath:@""];
NSNumber *amountSum = [transactions valueForKeyPath:@"@sum.amount"];

What’s even cooler about these Collection Operators is that you have the ability to sort collections (NSArray, NSSet, NSDictionary) using them.

NSSortDescriptor *sortByTrivia = [NSSortDescriptor sortDescriptorWithKey:@"trivia.@count" ascending:YES];
self.dataStore.locations = [NSMutableArray arrayWithArray:[self.dataStore.locations sortedArrayUsingDescriptors:@[sortByTrivia]]];

But be warned, you may not use collection operators for the key paths of your sort descriptors with fetch requests (NSFetchRequest). At least not yet in iOS7. You should fetch then apply the sort descriptor.

Happy sorting!

Leave a Comment