遇到求和、平均值、最大最小值等相關的需求,我們通常的做法就是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];
原文連結:http://www.jianshu.com/p/7d184d68b0d5