Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Random 如何从NSDictionary中选择随机键?_Random_Nsarray_Element_Nsdictionary - Fatal编程技术网

Random 如何从NSDictionary中选择随机键?

Random 如何从NSDictionary中选择随机键?,random,nsarray,element,nsdictionary,Random,Nsarray,Element,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; 我需

当我使用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:。那么我该如何实现这一点呢?

您可以使用(未定义的顺序)或(如果需要按值排序)获得一个键数组。需要记住的一件事(关于lastIndex)是,即使使用排序,随着字典的增长,相同的索引也可能引用不同的键值对

其中任何一个(尤其是keysSortedByValueUsingSelector)都会带来性能损失


编辑:因为字典是不可变的,所以您应该能够调用所有键一次,然后从中选择随机键。

您可以使用以下代码:

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

为了提高效率,可以在实例变量中缓存
。希望这有帮助

它是一个NSDictionary(不是NSMutableDictionary),所以它不会增长。它将在应用程序启动时使用[[NSDictionary alloc]initWithObjectsAndKeys:…,nil]显式创建;它起作用了。我所做的是调用所有密钥一次并将其存储在新的NSArray ivar中。奇怪的是,即使NSDictionary保持不变,也不能保证所有密钥总是以相同的顺序返回密钥。不过,希望NSArray*指向其返回值不会有问题。在您的例子中,我认为保留allKeys返回值没有任何错误。分配了一个新数组,因此结果不会直接指向内部数据结构。