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

祝您愉快开心 ^_^

原文地址:https://www.cnblogs.com/tianglin/p/3449580.html