2012-10-23 49 views
0

我有一个我想随机访问的对象字典。 它不一定是正确的随机,但只是有很大的变化。从字典中随机访问键

字典看起来像这样这样的:

'customer0' : '<Customer Object>' 
'customer1' : 'inactive' 
'customer2' : 'inactive' 
'customer3' : 'inactive' 
'customer4' : '<Customer Object>' 

的键对应将被用来表示一个客户在一场比赛中,基本上我希望他们不会出现在同一顺序的UI元素每次。

回答

3

关于随机数read more here on stack。所以,如果你有字符串键,你可以使用像这样的smth:

NSString *key = [NSString stringWithFormat:@"customer%d", arc4random()%5]; 
<customer object> *customObj = [yourDictionary objectForKey:key]; 
+0

干杯。我将它与一个while循环结合起来随机选择不活动的客户。 – Max

0

我没有测试过这一点,但这些方针的东西应该达到你的目标是什么了:

//create dictionary 
NSDictionary *dictionary = [NSDictionary dictionary]; 

//gather set of keys from array of keys 
NSSet *keys = [NSSet setWithArray:[dictionary allKeys]]; 

//gather random key 
NSString *key = [keys anyObject]; 

//gather dictionary value with key 
NSString *value = [dictionary objectForKey:key]; 

通过创建从字典键的NSArrayNSSet,您可以使用anyObject收集的数组中的随机密钥。

当然还有其他方法可以达到这个目的,但这是我能想到的最简洁的方法。

+0

当然,'NSSet'是无序的,但'anyObject'不会返回集合中的随机对象! – JustSid

+0

同意。但是这种方法似乎比使用arc4random更清晰。 NSSet文档指出:“返回的对象是在方便的时候选择的 - 选择不保证是随机的。” – CaptainRedmuff

2

伪代码:

  1. 创建结构的副本 - 你可以拿到钥匙到一个数组
  2. 选择从0随机整数n的副本-1
  3. 提取物的大小(如在检索和删除)在位置n直到尺寸==元件
  4. 重复从2)0