3

作成した plist からランダムに質問を表示する質問アプリを作りたいです。これが関数です (今のところ 7 つの質問しかありません)。

私の関数はランダムな質問をしますが、常に同じ質問で始まり、質問を繰り返すことができます。質問をランダムに繰り返しなしで生成するには、あなたの助けが必要です.

 currentQuestion=rand()%7;
 NSDictionary *nextQuestion = [self.questions objectAtIndex:currentQuestion];

    self.answer = [nextQuestion objectForKey:@"questionAnswer"];

    self.qlabel.text = [nextQuestion objectForKey:@"questionTitle"];

    self.lanswer1.text = [nextQuestion objectForKey:@"A"];

    self.lanswer2.text = [nextQuestion objectForKey:@"B"];

    self.lanswer3.text = [nextQuestion objectForKey:@"C"];

    self.lanswer4.text = [nextQuestion objectForKey:@"D"];
4

3 に答える 3

2

私はこのようにします(ARCでは、明確にするために余分に長く書き出されています):

@property (nonatomic,strong) NSDictionary *unaskedQuestions;

- (NSString *)nextRandomUnaskedQuestion {

    if (!self.unaskedQuestions) {
        // using your var name 'nextQuestion'.  consider renaming it to 'questions'
        self.unaskedQuestions = [nextQuestion mutableCopy];
    }

    if ([self.unaskedQuestions count] == 0) return nil;  // we asked everything

    NSArray *keys = [self.unaskedQuestions allKeys];
    NSInteger randomIndex = arc4random() % [allKeys count];
    NSString *randomKey = [keys objectAtIndex:randomIndex];
    NSString *nextRandomUnaskedQuestion = [self.unaskedQuestions valueForKey:randomKey];

    [self.unaskedQuestions removeObjectForKey:randomKey];
    return nextRandomUnaskedQuestion;
}
于 2012-11-15T16:03:31.037 に答える
2

rand()%7;常に一意の乱数列を生成します。

arc4random() % 7;代わりに使用してください。

currentQuestion=arc4random() %7;
于 2012-11-15T14:31:14.080 に答える
1
  1. 質問キーの配列を使用します。arrKeys という名前の配列があるとします --> [A]、[B]、[C]、[D]、...、[z]、nil
  2. (arc4random() % array.length-1) {Suresh の提案による} を使用して、配列の rendom インデックスを生成します。rand = 3 だとします。
  3. 配列 arrKeys @3 = D からキーを取得します。次に、NSDictionary から [nextQuestion objectForKey:@"D"] を使用し、配列から 'D' キーを [arrKeys removeObjectAtIndex:3] として削除します。次の質問で 1 ~ 3 の手順を繰り返します。
于 2012-11-15T14:44:08.360 に答える