Shuffling an array in objective-c [duplicate]

2020-02-04 05:58发布

Possible Duplicate:
What’s the Best Way to Shuffle an NSMutableArray?

I develop apps for iphone/iPad.I want to shuffle the objects stored in an NSArray.Is there any way to achieve it with objective-c?

2条回答
家丑人穷心不美
2楼-- · 2020-02-04 06:19

Add a category to NSMutableArray, with code provided by 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
查看更多
放荡不羁爱自由
3楼-- · 2020-02-04 06:20

See if this sample helps.

You can see this previous SO question too canonical way to randomize an NSArray in Objective C

查看更多
登录 后发表回答