相信每個程序員都會遇到求和、平均值、最大最小值等相關的需求,通常的做法就是for循環。在iOS開發中,系統API為我們提供了非常簡便的方法,我們來一睹為快。
首先我們定義一個數組:
NSArray *array= [NSArray arrayWithObjects:@"2.0",@"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];
|
新聞熱點
疑難解答