美文网首页
使用KVO对NSArray数据进行快速计算。

使用KVO对NSArray数据进行快速计算。

作者: anjohnlv | 来源:发表于2017-08-25 14:50 被阅读47次

    今天涉猎到NSArray一个以前自己没玩过的玩法,在这里稍作记录:

    数组计算 keyPath
    数组求和 @"@sum"
    数组求平均值 @"@avg"
    数组求最大值 @"@max"
    数组求最小值 @"@min"
    数组求个数 @"@count"

    只能对基本数据类型进行计算,如int(NSInteger),float(CGFloat)等。

    由于我们的数组对象都是NSObject类型,所以在使用时需要指明需要计算的类型。如:

    NSArray *numbers = @[@(1), @(2), @(4)];
    

    我们要求和,可以使用

    [numbers valueForKeyPath:@"@sum.intValue"] ;
    

    如果是浮点数求和

    [numbers valueForKeyPath:@"@sum.floatValue"] ;
    

    返回值均为NSNumber类型。
    这个方法还可以对Model数据进行快速计算。如:

    @interface Person : NSObject
    
    @property(nonatomic, strong)NSString *name;
    @property(nonatomic)NSInteger age;
    @property(nonatomic)CGFloat score;
    
    @end
    
    NSArray<Person *> *persons;
    

    我们要统计年龄最小的人

    [persons valueForKeyPath:@"@min.age"];
    

    要统计平均姓名长度

    [persons valueForKeyPath:@"@avg.name.length"];
    

    要统计有多少人有分数

    [persons valueForKeyPath:@"@count.score"];
    

    需要注意的是,这里的count,与[persons count]并不相同。后者计算的是一共有多少人,而这里统计的是一共多少人有分数。

    相关文章

      网友评论

          本文标题:使用KVO对NSArray数据进行快速计算。

          本文链接:https://www.haomeiwen.com/subject/zfqudxtx.html