如何从 NSDictionary 中选择随机键?
当我使用 NSArray 时,这很简单:
NSArray *array = ...
lastIndex = INT_MAX;
...
int randomIndex;
do {
randomIndex = RANDOM_INT(0, [array count] - 1);
} while (randomIndex == lastIndex);
NSLog(@"%@", [array objectAtIndex:randomIndex]);
lastIndex = randomIndex;
我需要跟踪最后一个索引,因为我想要随机的感觉。 也就是说,我不想连续两次获取相同的元素。 所以它不应该是“真正的”随机性。
据我所知,NSDictionary 没有类似 -objectAtIndex: 的东西。 那么我该如何实现这一点呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 allKeys (未定义顺序)或 keysSortedByValueUsingSelector(如果您想按值排序)。
要记住的一件事(关于lastIndex)是,即使进行排序,随着字典的增长,相同的索引也可能会引用不同的键值对。其中任何一个(但尤其是keysSortedByValueUsingSelector)将会带来性能损失。
编辑:由于字典不可变,因此您应该只能调用 allKeys 一次,然后从中选择随机键。
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.
您可以使用下面的代码:
为了提高效率,您可以将
keys
缓存在实例变量中。 希望这可以帮助。You could use the code below:
To make it more efficient, you can cache
keys
in an instance variable. Hope this helps.