从plist中随机选择

时间:2011-08-31 21:47:24

标签: objective-c

  

可能重复:
  create random integers for quiz using plist

使用xcode,如何从我的plist中随机选择?我在我的plist中创建了84个问题,并且想要在用户单击按钮时随机选择10来创建测验。

到目前为止我已经

NSString *plistFile = [[NSBundle mainBundle] pathForResource:@"global" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsofFile:plistFile];
NSLog(@"%@",[dict objectForKey:@"1"]);
NSLog(@"%@",[dict objectForKey:@"2"]);
NSLog(@"%@",[dict objectForKey:@"3"]);

Global是plist名称,@“1”,@“2”等是每个不同问题的名称。这是我用随机问题创建测验的漫长道路。

3 个答案:

答案 0 :(得分:0)

如果您的密钥确实是@"1"@"2"等,那么您只需选择一个随机数并选择该对象即可。例如,

int i = (arc4random() % 84) + 1;
[dict objectForKey:[NSString stringWithFormat:@"%d",i]];

但是,在这种情况下,在我看来,您应该使用NSArray个问题而不是NSDictionary。然后你可以简单地做

int i = arc4random() % 84;
[questionArray objectAtIndex:i];

要从10种可能性中选择84个不同的随机数,最简单的可能就是保留NSMutableArray个数字。然后,如上所述生成另一个随机数,然后在将其添加到数组之前,检查它是否已经存在。例如:

NSMutableArray *questionNumbers = [[NSMutableArray alloc] init];
int i;
while ([questionNumbers count] < 10) {
    i = arc4random() % 84;
    if (![questionNumbers containsObject:[NSNumber numberWithInt:i]]) {
        [questionNumbers addObject:[NSNumber  numberWithInt:i]];
    }
}

如果您选择这种方法,请不要忘记在某些时候发布questionNumbers

答案 1 :(得分:0)

您检查了this。然后,您需要拥有自己的算法,以保持其唯一的10个数字。

答案 2 :(得分:0)

您可以使用其他问题的解决方案来实现此目的:

What's the Best Way to Shuffle an NSMutableArray?

使用该解决方案中的-shuffle方法,您可以执行以下操作:

- (NSArray *)getRandomObjectsFromDictionary:(NSDictionary *)dict numObjects:(NSInteger)numObjects
{
    NSMutableArray *keys = [[[dict allKeys] mutableCopy] autorelease];
    [keys shuffle];

    numObjects = MIN(numObjects, [keys count]);

    NSMutableArray randomObjects = [NSMutableArray arrayWithCapacity:numObjects];
    for (int i = 0; i < numObjects; i++) {
        [randomObjects addObject:[dict objectForKey:[keys objectAtIndex:i]]];
    }
    return [NSArray arrayWithArray:randomObjects];
}

这适用于任何NSDictionary,无论密钥是什么。

相关问题