Shuffling with Objective-C Categories

One of the neat features of Objective-C programming is categories. Categories give the ability to add discrete bits of functionality on existing classes. Think of them as lightweight inheritance; I can add one or more methods to an existing class without having to create a custom subclass. There’s a bunch more you can do with categories as described in the Mac Dev Center.

In a current project I’m working on, I’m dealing with many arrays whose objects need to be in a random order. There are many ways of accomplishing the randomization of array order, but having implemented the Fisher-Yates shuffling algorithm in other languages and projects, I decided to implement an Objective-C version of it. It’s a deceivingly simple algorithm, and there’s a great post on why the Fisher-Yates method beats the pants off a naive shuffling algorithm over at Coding Horror.

I decided the easiest implementation would be add the category directly into NSArray and NSMutableArray. This way all the shuffling logic is fully encapsulated within those classes. Another article got me started on how to do this with the shuffling algorithm I wanted to use. This got me 90% the way there.

Basically all you do is create a new header and implementation file. For the interface, you define the new category and methods for both NSArray and NSMutableArray:

Or automatically shuffling a collection of songs a user has picked using the MPMediaPickerController (you can also shuffle songs using the shuffleMode property of the MPMusicPlayerController, but they don’t get shuffled until they are played):

// mediaItemCollection.items is an NSArray,
// so we create a new MPMediaItemCollection using -shuffledArray.
MPMediaItemCollection *shuffledCollection = [MPMediaItemCollection collectionWithItems:[mediaItemCollection.items shuffledArray]];

// Now we've got a new collection of shuffled items.
[self playMediaCollection:shuffledCollection];
}

I’ve glossed over many details here here in an attempt to show a practical use for categories and shuffling. If you’re interested in learning more, I’d recommend checking out the links in this post. They are excellent references.