Thursday, September 10, 2009

Shuffle/Randomize Arrays (iPhone)

iPhone programming is a bit different task, you have to write a lot of code just for a small task. Have you ever need to randomize an array of items? It's a task that, for some reason, needs to be used a lot (at least for me). So, I am showing you a simple way to handle this task.

ShuffleArray.h

#import "UIKit/UIKit.h"

@interface NSArray(Shuffle)
-(NSArray *)shuffledArray;
@end

ShuffleArray.m

#import "ShuffleArray.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