How do I select a random key from an NSDictionary?

一笑奈何 提交于 2019-12-13 12:29:39

问题


When I was using an NSArray, it was easy:

NSArray *array = ...
lastIndex = INT_MAX;
...
int randomIndex;
do {
  randomIndex = RANDOM_INT(0, [array count] - 1);
} while (randomIndex == lastIndex);
NSLog(@"%@", [array objectAtIndex:randomIndex]);
lastIndex = randomIndex;

I need to keep track of the lastIndex because I want the feeling of randomness. That is, I don't want to get the same element twice in a row. So it shouldn't be "true" randomness.

From what I can tell, NSDictionary doesn't have something like -objectAtIndex:. So how do I accomplish this?


回答1:


You can get an array of keys with allKeys (undefined order) or keysSortedByValueUsingSelector (if you want sorting by value). One thing to keep in mind (regarding lastIndex) is that even with sorting, the same index may come to refer to a different key-value pair as the dictionary grows.

Either of these (but especially keysSortedByValueUsingSelector) will come with a performance penalty.

EDIT: Since the dictionary isn't mutable, you should just be able to call allKeys once, and then just pick random keys from that.




回答2:


You could use the code below:

- (YourObjectType *)getRandomObjectFromDictionary:(NSDictionary *)dictionary
{
    NSArray *keys = dictionary.allKeys;
    return dictionary[keys[arc4random_uniform((int)keys.count)]];
}

To make it more efficient, you can cache keys in an instance variable. Hope this helps.



来源:https://stackoverflow.com/questions/1112267/how-do-i-select-a-random-key-from-an-nsdictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!