lonelysoul

Happy share, happy life.

导航

iOS中打乱数组的顺序

实现NSMutableArray的分类,

NSMutableArray+Shuffling.h

@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end

NSMutableArray+Shuffling.m

@implementation NSMutableArray (Shuffling)

- (void)shuffle
{
    static BOOL seeded = NO;
    if(!seeded) {
        seeded = YES;
        srandom(time(NULL));
    }
    
    NSUInteger count = [self count];
    for (NSUInteger i = 0; i < count; ++i) {
        // Select a random element between i and end of array to swap with.
        int nElements = count - i;
        int n = (random() % nElements) + i;
        [self exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
}

@end

 

 

祝您愉快开心 ^_^

posted on 2013-11-29 14:50  lonelysoul  阅读(338)  评论(0编辑  收藏  举报