<分区>
Possible Duplicate:
What’s the Best Way to Shuffle an NSMutableArray?
我为 iphone/iPad 开发应用程序。我想打乱存储在 NSArray 中的对象。有什么方法可以用 objective-c 实现吗?
<分区>
Possible Duplicate:
What’s the Best Way to Shuffle an NSMutableArray?
我为 iphone/iPad 开发应用程序。我想打乱存储在 NSArray 中的对象。有什么方法可以用 objective-c 实现吗?
最佳答案
向 NSMutableArray 添加类别,使用 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
关于iphone - 在 objective-c 中改组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5659718/