KVC Collection Operators
KVC Collection Operators allows actions to be performed on a collection using key path notation in valueForKeyPath:. Any time you see @ in a key path, it denotes a particular aggregate function whose result can be returned or chained, just like any other key path.
→ nshipster.com/kvc-collection-operators/
The article discusses Key-Value Coding (KVC) Collection Operators in Objective-C, which provide a concise, Ruby-like syntax for performing aggregate operations on collections using valueForKeyPath:
.
These operators, denoted by @
in key paths, fall into three categories:
- Simple Collection Operators (
@count
,@sum
,@avg
,@max
,@min
) return scalars like numbers or dates (e.g.,[products valueForKeyPath:@"@avg.price"]
yields 881.50); - Object Operators (
@unionOfObjects
,@distinctUnionOfObjects
) return arrays of property values, with the latter removing duplicates; - Array and Set Operators (
@distinctUnionOfArrays
,@unionOfArrays
,@distinctUnionOfSets
) combine values from nested collections
Using a Product
class example, the article demonstrates how operators automatically handle scalar boxing into NSNumber
or NSValue
. It also highlights a custom DSL extension by swizzling valueForKeyPath:
to support complex queries, though advises using NSPredicate
for clarity.
Written before Swift’s dominance, the article showcases Objective-C’s expressive power, with Swift’s modern syntax enhancing similar KVC patterns for efficient collection manipulation.
Category:
Tags:
Year: