Skip to content

Instantly share code, notes, and snippets.

@fadookie
Created December 27, 2012 22:32
Show Gist options
  • Save fadookie/4392708 to your computer and use it in GitHub Desktop.
Save fadookie/4392708 to your computer and use it in GitHub Desktop.
Retrieve random object from NSSet
//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