NSMutableArrayにカテゴリを追加することでこれを解決しました。
編集:ラッドによる回答のおかげで不要なメソッドを削除しました。
編集: GregoryGoltsovによる回答とmihoとblahdiblahによるコメントのおかげで変更(arc4random() % nElements)
されましたarc4random_uniform(nElements)
編集:ロンによるコメントのおかげでループの改善
編集: Mahesh Agrawalによるコメントのおかげで、配列が空ではないことのチェックを追加しました
// 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
{
NSUInteger count = [self count];
if (count <= 1) return;
for (NSUInteger i = 0; i < count - 1; ++i) {
NSInteger remainingCount = count - i;
NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t )remainingCount);
[self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
}
}
@end