首页 > 编程语言 > 详细

为数组 NSArray添加一些 分类方法

时间:2017-06-15 12:02:47      阅读:371      评论:0      收藏:0      [点我收藏+]

#import "NSArray+Operation.h"

 

@implementation NSArray (Operation)

 // 数组的平均数

-(float)averageValueOfElements{

    NSNumber * value = [self valueForKeyPath:@"@avg.floatValue"];

    return value.floatValue;

}

// 每个元素的和

-(float)sumValueOfElements{

    NSNumber * value = [self valueForKeyPath:@"@sum.floatValue"];

    return value.floatValue;

}

// 返回随机的子数组 

-(NSArray *)randomizedArray{

    if (self.count == 0) {

        return self;

    }

    

    NSMutableArray *results = [NSMutableArray arrayWithArray:self];

    NSUInteger i = [results count];

    while(--i > 0) {

        int j = arc4random() % (i+1);

        [results exchangeObjectAtIndex:i withObjectAtIndex:j];

    }

    return [NSArray arrayWithArray:results];

}

 //返回随机一个元素

- (id)hh_randomObject {

    NSUInteger count = self.count;

    return ((count > 0) ? self[arc4random_uniform((uint32_t)count)] : nil);

}

 // 返回指定的某个

- (id)hh_objectOrNilAtIndex:(NSUInteger)index {

    return index < self.count ? self[index] : nil;

}

为数组 NSArray添加一些 分类方法

原文:http://www.cnblogs.com/1018475062qq/p/7016617.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!