在objective-c中混洗一个数组

时间:2011-04-14 07:05:13

标签: iphone ios ipad nsmutablearray nsarray

  

可能重复:
  What’s the Best Way to Shuffle an NSMutableArray?

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

2 个答案:

答案 0 :(得分:12)

使用code provided by Kristopher Johnson -

向NSMutableArray添加类别
//  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

答案 1 :(得分:2)

查看此sample是否有帮助。

您也可以看到此前的SO问题canonical way to randomize an NSArray in Objective C