iOS 获取数组最大值最小值
2018-01-22 本文已影响1835人
梦蕊dream
如何优雅的处理数组?如何不使用遍历方法处理。
1.获取数组最大值、最小值
保证数组里存储NSNumber
对象
例如处理接口中数据:
NSMutableArray *price = [NSMutableArray array];
for (NSDictionary *item in arr) {
[price addObject: [NSNumber numberWithFloat:[item[@"price"] floatValue]]];
}
CGFloat maxPrice = [[price valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat minPrice = [[price valueForKeyPath:@"@min.floatValue"] floatValue];
重点参数:
@"@max.floatValue"(获取最大值),
@"@min.floatValue"(获取最小值),
@"@avg.floatValue" (获取平均值),
@"@count.floatValue"(获取数组大小)
KVC,使用"self"
NSNumber *max=[numbers valueForKeyPath:@"@max.self"];
NSNumber *min=[numbers valueForKeyPath:@"@min.self"];
代码块
__block float xmax = -MAXFLOAT;
__block float xmin = MAXFLOAT;
[numbers enumerateObjectsUsingBlock:^(NSNumber *num, NSUInteger idx, BOOLBOOL *stop) {
float x = num.floatValue;
if (x < xmin) xmin = x;
if (x > xmax) xmax = x;
}];
2.数组排序
NSArray *numbers = @[@2.1, @8.1, @5.0, @0.3];
numbers = [numbers sortedArrayUsingSelector:@selector(compare:)];
float min = [numbers[0] floatValue];
float max = [[numbers lastObject] floatValue];