Key-Value Coding aggregation operations on collections

If you have ever worked with SQL queries and the aggregate functions (or in worst case with spreadsheet applications like Excel or Numbers), this topic will be familiar to you.

It is usually overlooked, but the Key-Value Coding can also benefit from those functions on collections, like NSArray or NSSet. Obviously the type should support those operations, for example, it would be barely successful to ask for sum on a set containing NSStrings.

Aggregate functions in Key-Value Coding

Let’s take a look what basic aggregation operations we have, similar to the SQL: @count, @sum, @avg, @max, and @min. There are also other operations, for the full list, you can check the documentation.

The key point here is the same method used for the Key-Value Coding, the valueForKeyPath:. If you want to use the aggregate functions on any set, you should use [anySet valueForKeyPath:@“@aggregate_function.key”];. Notice, that we are using the @ symbol before the aggregate.

However, @count doesn’t make sense for me, as you can always send the count message to the set, the others could be really interesting and helpful.

Aggregate!

Let see some basic example for NSNumbers and dates. Obviously @avg and @sum will fail on NSDates.

Since the aggregate should be applied on the set, which is contains the atomic structures, I used .self after the aggregate function.

The thing is getting more interesting, when you are using array of Objects, for example:

As you can see I created a really basic class (PMOTransaction), and 3 instances, which I added to a collection. Then I used the property names as keys, and applied the aggregate on them.

I hope this small example helps to you out in some cases when you need the minimum or a maximum from a collection.

Update:retsotrembla on Reddit mentioned 2 additional resource: Defining your own aggregate functions and the NSHipster’s KVC Collection Operators.


Leave a Reply