NSArray-Shuffle.h
#import
@interface NSArray(Shuffle)
-(NSArray *)shuffledArray;
@end
NSArray-Shuffle.m
#import "NSArray-Shuffle.h"
@implementation NSArray(Shuffle)
-(NSArray *)shuffledArray
{
NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self count]];
NSMutableArray *copy = [self mutableCopy];
while ([copy count] > 0)
{
int index = arc4random() % [copy count];
id objectToMove = [copy objectAtIndex:index];
[array addObject:objectToMove];
[copy removeObjectAtIndex:index];
}
[copy release];
return array;
}
@end
No comments:
Post a Comment