Created
December 27, 2012 22:32
-
-
Save fadookie/4392708 to your computer and use it in GitHub Desktop.
Retrieve random object from NSSet
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
//Implemented based on the pseudo-code in http://stackoverflow.com/a/9981965/350761 | |
int randomIndex = arc4random() % [set count]; | |
__block int currentIndex = 0; | |
__block id selectedObj = nil; | |
[set enumerateObjectsUsingBlock:^(id obj, BOOL *stop) { | |
if (randomIndex == currentIndex) { selectedObj = obj; *stop = YES; } | |
else currentIndex++; | |
}]; | |
return selectedObj; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment