How to shuffle a NSMutableArray [Objective-C]

The Objective-C NSArray object doesn’t have a specific function to shuffle the elements of the array.

With this simple code we can shuffle one NSMutableArray randomly. We will use the exchangeObjectAtIndex method for exchange items within the array and arc4random to get a random number we use to exchange items.

1
2
3
4
5
6
7
/* myArray is a NSMutableArray with some objects */
NSUInteger count = [myArray count];
for (NSUInteger i = 0; i < count; ++i) {
	int nElements = count - i;
	int n = (arc4random() % nElements) + i;
	[myArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}

Very useful, right? 🙂

Share... Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on TumblrShare on RedditEmail this to someone

0 Comments

Leave a Comment

Your email address will not be published. Required fields are marked *

Comment *
Your Name *
Your Email *
Website