如何从NSDictionary中选择随机密钥? [英] How do I select a random key from an NSDictionary?

查看:54
本文介绍了如何从NSDictionary中选择随机密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用NSArray时,很容易:

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;

我需要跟踪lastIndex,因为我想要随机的感觉。也就是说,我不想连续两次获得相同的元素。因此,它不应该是真正的随机性。

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.

据我所知,NSDictionary没有-objectAtIndex:之类的东西。那么我该如何完成呢?

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

推荐答案

您可以使用 allKeys (未定义的顺序)或 keysSortedByValueUsingSelector (如果您想按值排序)。 要记住的一件事(关于lastIndex)是,即使进行排序,随着字典的增长,相同的索引也可能会引用不同的键值对。

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.

这两个选项(但尤其是keysSortedByValueUsingSelector)都会带来性能损失。

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

编辑:由于字典不可变,因此您应该能够一次调用allKeys,然后从中随机选择密钥。

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

这篇关于如何从NSDictionary中选择随机密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆