Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grab random entry in NSDictionary

Is there a way to grab a totally random key in the NSDictionary?

NSString *key = [enumeratorForKeysInDictionary nextObject]; 

I have this code which iterates over the dictionary in a non-random way.

Should I add all the keys to an NSSet and then pull randomly from there?

Is there a more efficient way to do this?

like image 593
stackOverFlew Avatar asked Feb 26 '26 21:02

stackOverFlew


2 Answers

See this:

NSArray *array = [dictionary allKeys];
int random = arc4random()%[array count];
NSString *key = [array objectAtIndex:random];
like image 107
aks.knit1108 Avatar answered Mar 01 '26 10:03

aks.knit1108


NSArray* allKeys = [dictionary allKeys];
id randomKey = allKeys[arc4random_uniform([allKeys count])];
id randomObject = dictionary[randomKey];
like image 45
mopsled Avatar answered Mar 01 '26 11:03

mopsled