Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to shuffle a NSMutableArray [Objective-C]
/* 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];
}
@josephchang10

This comment has been minimized.

Copy link
Owner Author

josephchang10 commented Apr 18, 2017

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.