遇到求和、平均值、最大最小值等相关的需求,我们通常的做法就是for循环。其实iOS系统API已经为我们提供了非常简便的方法,来来来,跟着我来看一看。
首先我们定义一个数组:
</pre> <pre name="code" class="objc">NSArray *array= [NSArray arrayWithObjects:@"1",@"2",@"2.3",@"3.0",@"4.0",@"10",nil];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
通过以上方法,完美获取到array的各种统计值。
那么问题来了,如果是自定义的对象数组,如何获取这些统计值呢?比如前几期文章我们自定义的Person:
@interface Person
@property NSString *name;
@property NSInteger age;
@end
假设某个班级有很多学生,我们将这些学生的信息都存到数组personArray,然后获取这些Person的平均年龄,最大最小年龄,方法是:
[[personArray valueForKeyPath:@"@avg.age"] integerValue];
[[personArray valueForKeyPath:@"@max.age"] integerValue];
[[personArray valueForKeyPath:@"@min.age"] integerValue];
网友评论