KVC支持的聚合运算
- sum 求和
- max 最大值
- min 最小值
- avg 平均值
- count 数量
使用方法
新建一个类Person
,里面存放一个属性age
#import <Foundation/Foundation.h>
@interface Person : NSObject
/** 年龄 */
@property (nonatomic, assign) NSUInteger age;
@end
创建一个数组,存放Person
对象
NSMutableArray<Person *> *persons = [NSMutableArray array];
for (int i = 1; i <= 5; i++) {
Person *p = [[Person alloc] init];
p.age = i;
[persons addObject:p];
}
使用@sum
@min
@max
@avg
@count
进行聚合运算
NSInteger sum = [[persons valueForKeyPath:@"@sum.age"] integerValue];
NSInteger min = [[persons valueForKeyPath:@"@min.age"] integerValue];
NSInteger max = [[persons valueForKeyPath:@"@max.age"] integerValue];
float avg = [[persons valueForKeyPath:@"@avg.age"] floatValue];
NSInteger count = [[persons valueForKeyPath:@"@count.age"] integerValue];
NSLog(@"sum=%zd", sum);
NSLog(@"min=%zd", min);
NSLog(@"max=%zd", max);
NSLog(@"avg=%g", avg);
NSLog(@"count=%zd", count);
打印结果
数组中直接存放数值的情况
直接使用@运算符.floatValue
NSArray<NSNumber *> *arr = @[@1, @2, @3, @4];
NSNumber *avg = [arr valueForKeyPath:@"@avg.floatValue"];
NSNumber *sum = [arr valueForKeyPath:@"@sum.integerValue"];
NSLog(@"avg=%@", avg);
NSLog(@"sum=%@", sum);
打印结果