如何在循环中排除以前随机选择的NSArrays

时间:2012-02-22 16:15:58

标签: objective-c cocoa-touch for-loop nsarray

我是Objective-C的新手,我正在尝试创建一个简单的字典样式应用程序供个人使用。现在我正在尝试创建一个循环,打印已添加到NSArray的随机选择的NSDictionary。我想只打印一次每个数组。这是我正在使用的代码:

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:是否有用。

2 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分: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);
}