2012-02-22 108 views
1

我是Objective-C的新手,我試圖創建一個簡單的字典樣式的應用程序供個人使用。現在我試圖做一個循環,打印隨機選擇的NSArray s已被添加到NSDictionary。我想只打印一次每個數組。這裏是我正在使用的代碼:如何在循環中排除先前隨機選擇的NSArrays

NSArray *catList = [NSArray arrayWithObjects:@"Lion", @"Snow Leopard", @"Cheetah", nil]; 
NSArray *dogList = [NSArray arrayWithObjects:@"Dachshund", @"Pitt Bull", @"Pug", nil]; 
... 
NSMutableDictionary *wordDictionary = [[NSMutableDictionary alloc] init]; 
[wordDictionary setObject: catList forKey:@"Cats"]; 
[wordDictionary setObject: dogList forKey:@"Dogs"]; 
... 
NSInteger keyCount = [[wordDictionary allKeys] count]; 
NSInteger randomKeyIndex = arc4random() % keyCount; 

int i = keyCount; 

for (i=i; i>0; i--) { 
    NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex]; 
    NSMutableArray *randomlySelectedArray = [wordDictionary objectForKey:randomKey]; 
    NSLog(@"%@", randomlySelectedArray); 
} 

此代碼打印相同的數組「i」次。關於如何排除先前打印的數組再次被打印的指針?

我在想如果removeObjectForKey:可以有任何用處。

+0

是'removeObjectForKey'你合適嗎?這將從字典中移除數組。 – sch 2012-02-22 16:25:07

+0

我認爲removeObjectForKey,但不知道如何在循環中實現它! – 2012-02-22 16:36:47

回答

2

你只需要在每次經過時間重新計算隨機密鑰索引循環,然後,如您所示,使用removeObjectForKey:

事情是這樣的:

NSArray *catList = [NSArray arrayWithObjects:@"Lion", @"Snow Leopard", @"Cheetah", nil]; 
NSArray *dogList = [NSArray arrayWithObjects:@"Dachshund", @"Pitt Bull", @"Pug", nil]; 

//... 

NSMutableDictionary *wordDictionary = [[NSMutableDictionary alloc] init]; 
[wordDictionary setObject: catList forKey:@"Cats"]; 
[wordDictionary setObject: dogList forKey:@"Dogs"]; 

//... 

while ([wordDictionary count] > 0) {  
    NSInteger keyCount = [wordDictionary count]; 
    NSInteger randomKeyIndex = arc4random() % keyCount; 
    NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex]; 
    NSMutableArray *randomlySelectedArray = [wordDictionary objectForKey:randomKey]; 
    NSLog(@"%@", randomlySelectedArray); 

    [wordDictionary removeObjectForKey: randomKey]; 
} 
+0

謝謝!那完美的@monolo作品。 – 2012-02-22 17:03:12

1

在您的代碼中,您將生成一個隨機randomKeyIndex,然後在循環中使用它而不更改其值i次。所以你得到i次相同的數組。

NSInteger randomKeyIndex = arc4random() % keyCount; 
// ... 
for (i=i; i>0; i--) { 
    NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex]; 
    // ... 
} 

至於你說removeObjectForKey是一個選擇,你可以改變你的代碼是這樣的:

NSInteger keyCount = [[wordDictionary allKeys] count]; 

for (i=keyCount; i>0; i--) { 
    NSInteger randomKeyIndex = arc4random() % keyCount; 
    NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex]; 
    NSMutableArray *randomlySelectedArray = [wordDictionary objectForKey:randomKey]; 
    [wordDictionary removeObjectForKey:randomKey]; 
    keyCount--; 
    NSLog(@"%@", randomlySelectedArray); 
} 
+0

這就是我卡在@sch的地方。我一直無法弄清楚如何改變它的值並保持它的隨機性。 – 2012-02-22 16:35:58

+0

@OrpheusMercury - 在我的文章結尾處看到代碼,它告訴你如何改變'randomKeyIndex'的值。 – sch 2012-02-22 16:37:46

+0

這就是我一直在尋找的!非常感謝你的幫助。 – 2012-02-22 17:04:10