在objective-c中重排数组

可能重复:
什么是最好的方式来洗牌NSMutableArray?

我开发iPhone / iPad应用程序。我想洗牌存储在一个NSArray中的对象。是否有任何方法来实现它与objective-c?

添加一个类别到NSMutableArray, 代码由Kristopher Johnson提供 –

// NSMutableArray_Shuffling.h #if TARGET_OS_IPHONE #import <UIKit/UIKit.h> #else #include <Cocoa/Cocoa.h> #endif // This category enhances NSMutableArray by providing // methods to randomly shuffle the elements. @interface NSMutableArray (Shuffling) - (void)shuffle; @end // NSMutableArray_Shuffling.m #import "NSMutableArray_Shuffling.h" @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 

看看这个样本是否有帮助。

你可以看到这个以前的SO问题太规范的方式来随机化目标C中的一个NSArray