2011-08-31 66 views
-4

可能重複:
create random integers for quiz using plist隨機抽取的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」 等都是爲每個不同的問題的名稱。這是我用隨機問題創建測驗的很長一段路。

+0

非常重複的問題。 –

回答

0

如果你的鑰匙真的是@"1",@"2"等,那麼你可以選擇一個隨機數並選擇該對象。例如,

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

然而,在這種情況下,我認爲你應該不是有問題,而不是一個NSDictionaryNSArray。然後,你可以簡單地做

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

要想從84可能性選擇10不同的隨機數,最簡單的可能只是爲了保持號碼的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

0

你檢查了this。然後,你需要有你自己的算法來保持它唯一的10個數字。

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,不管鑰匙是什麼。