2012-10-23 51 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