集合運算符是一個特殊的Key Path,作用于集合材鹦,可以作為參數(shù)傳遞給 valueForKeyPath: 方法
①簡單集合運算符
@avg逝淹,@count,@max桶唐,@min栅葡,@sum
<p>
②對象運算符
比集合運算符稍微復雜,能以數(shù)組的方式返回指定的內(nèi)容尤泽,一共有兩種:
</p>
@distinctUnionOfObjects
@unionOfObjects
<p>
它們的返回值都是NSArray欣簇,區(qū)別是前者返回的元素都是唯一的,是去重以后的結(jié)果安吁;后者返回的元素是全集醉蚁。
</p>
例子:
@interface Product
@property (nonatomic,strong) NSString *name;
@property (nonatomic)CGFloat price;
@end
//Product 數(shù)組
NSArray *productList = ...
//獲得product總個數(shù)
NSInteger count = [[productList valueForKeyPath:@"@count"] integerValue];
//獲得product價格總和
CGFloat sumPrice = [[productList valueForKeyPath:@"@sum.price"] floatValue];
//獲得product價格平均值
CGFloat sumPrice = [[productList valueForKeyPath:@"@avg.price"] floatValue];
//獲得product價格列表
NSArray *priceList = [productList valueForKeyPath:@"@unionOfObjects.price"];