Created
April 18, 2017 10:25
-
-
Save josephchang10/8b9e1b2ab1eb1e7c135dde96aec4c7c1 to your computer and use it in GitHub Desktop.
How to shuffle a NSMutableArray [Objective-C]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.