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

#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;

}

posted on 2017-06-15 11:28  1018475062  阅读(147)  评论(0编辑  收藏  举报