在objective-c中混洗一个数组

Har*_*sad 10 iphone nsmutablearray nsarray ipad ios

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

我为iphone/iPad开发应用程序.我想要对存储在NSArray中的对象进行洗牌.有没有办法用objective-c来实现它?

Sau*_*abh 12

添加一个类别到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
Run Code Online (Sandbox Code Playgroud)

  • 复制别人的答案不是好习惯:<http://stackoverflow.com/questions/56648/whats-the-best-way-to-shuffle-an-nsmutablearray> (13认同)