【Collection Operators】
Collection operators are specialized key paths that are passed as the parameter to the valueForKeyPath:
method. The operator is specified by a string preceded by an at sign (@
). The key path on the left side of the collection operator, if present, determines the array or set, relative to the receiver, that is used in the operation. The key path on the right side of the operator specifies the property of the collection that the operator uses. Figure 1 illustrates the operator key path format.
All the collection operators, with the exception of @count
, require a key path to the right of the collection operator.
Note: It is not currently possible to define your own collection operators.
Simple Collection Operators
NSNumber *transactionAverage = [transactions valueForKeyPath:@"@avg.amount"];
NSNumber *numberOfTransactions = [transactions valueForKeyPath:@"@count"];
NSDate *latestDate = [transactions valueForKeyPath:@"@max.date"];
NSDate *earliestDate = [transactions valueForKeyPath:@"@min.date"];
NSNumber *amountSum = [transactions valueForKeyPath:@"@sum.amount"];
Object Operators
NSArray *payees = [transactions valueForKeyPath:@"@distinctUnionOfObjects.payee"];
NSArray *payees = [transactions valueForKeyPath:@"@unionOfObjects.payee"];
// Important: These operators raise an exception if any of the leaf objects is nil.
Array and Set Operatorsw
NSArray *payees = [arrayOfTransactionsArrays valueForKeyPath:@"@distinctUnionOfArrays.payee"];
NSArray *payees = [arrayOfTransactionsArrays valueForKeyPath:@"@unionOfArrays.payee"];
@distinctUnionOfSets
Important: These operators raise an exception if any of the leaf objects is nil.