iOS 获取数组最大值最小值

如何优雅的处理数组?如何不使用遍历方法处理。

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];  
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,366评论 30 472
  • 设计模式是什么? 你知道哪些设计模式,并简要叙述? 设计模式是一种编码经验,就是用比较成熟的逻辑去处理某一种类型的...
    不懂后悔阅读 4,218评论 0 53
  • 设计模式是什么? 你知道哪些设计模式,并简要叙述? 设计模式是一种编码经验,就是用比较成熟的逻辑去处理某一种类型的...
    small_Sun阅读 3,214评论 0 4
  • 设计模式是什么? 你知道哪些设计模式,并简要叙述? 设计模式是一种编码经验,就是用比较成熟的逻辑去处理某一种类型的...
    Jt_Self阅读 4,134评论 0 4
  • 今天我享受了一个静谧的午后时光,徜徉在家的沙发里,没有孩童的喧闹,只有空气和我,静静的假寐着,有丝丝缕缕的阳光洒下...
    薛公子鸣魅阅读 2,720评论 0 0