收藏iOS开发iOS Developer

你还在写for循环求和吗?

2016-09-01  本文已影响1307人  充电实践

        相信每个程序员都会遇到求和、平均值、最大最小值等相关的需求,通常的做法就是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]; 

       后续,我会将项目开发中的很多技巧记录下来,供需要的童鞋参考,让大家少走一些弯路,感谢您的持续关注。

上一篇下一篇

猜你喜欢

热点阅读