Grab random entry in NSDictionary

2019-07-04 18:57发布

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?

7条回答
Summer. ? 凉城
2楼-- · 2019-07-04 19:34

See this:

NSArray *array = [dictionary allKeys];
int random = arc4random()%[array count];
NSString *key = [array objectAtIndex:random];
查看更多
登录 后发表回答