iphoneiosnsdictionarynsset

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?


Solution

  • See this:

    NSArray *array = [dictionary allKeys];
    int random = arc4random()%[array count];
    NSString *key = [array objectAtIndex:random];