检查的NSMutableArray包含一个int

检查的NSMutableArray包含一个int

本文介绍了检查的NSMutableArray包含一个int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提出这要求用户一系列问题的应用程序。问这个问题取决于随机 INT 生产。当 INT 时,我想将它添加到的NSMutableArray ,然后检查数组包含一个数字被选择的随机数的下一次。我目前使用以下code要做到这一点:

I am making an app which asks the user a series of questions. The question asked depends on the random int produced. When an int is used, I want to add it to an NSMutableArray, and then check if the array contains a number the next time a random number is chosen. I am currently using the following code to do this:

- (void) selectQuestionNumber {
textNum = lowerBounds + arc4random() % (upperBounds - lowerBounds);

if ([previousQuestions containsObject:[NSNumber numberWithInt:textNum]]) {
    [self selectQuestionNumber];
    NSLog(@"The same question number appeared!");
} else {
    questionLabel.text = [self nextQuestion];
    [self questionTitleChange];

    NSLog(@"New question made");
}
[previousQuestions addObject:[NSNumber numberWithInt:textNum]];
}

不过,code 的NSLog(@出现了同样的问题数!); 在控制台中从未显示,即使在同一个问题会出现两次。

However, the code NSLog(@"The same question number appeared!"); is never shown in the console, even when the same question will appear twice.

我的code显然是不起作用的,所以有什么code,我可以用它来检查,​​如果一个NSMutable数组包含一个 INT

My code is obviously non-functional, so what code can I use to check if an NSMutable array contains an int?

推荐答案

原液(适用于阵列和设置):

Original solution (works with Array and Set):

-(void)selectQuestionNumber
 {
   textNum = lowerBounds + arc4random() % (upperBounds - lowerBounds);

    NSPredicate *predicate =  [NSPredicate predicateWithFormat:@"intValue=%i",textNum];
    NSArray *filteredArray = [previousQuestions filteredArrayUsingPredicate:predicate];

    if ([filteredArray count]) {
        [self selectQuestionNumber];
        NSLog(@"The same question number appeared!");
    } else {
        questionLabel.text = [self nextQuestion];
        [self questionTitleChange];

        NSLog(@"New question made");
    }
    [previousQuestions addObject:[NSNumber numberWithInt:textNum]];
}

最好的解决方案,以及更好的性能,特别是具有与mutableSet(据邓肯C)。

Best solution, and better performance, especialy with mutableSet ( According to Duncan C).

 -(void)selectQuestionNumber
{

textNum = lowerBounds + arc4random() % (upperBounds - lowerBounds);

if ([previousQuestions containsObject:[NSNumber numberWithInteger:textNum]]) {
    [self selectQuestionNumber];
    NSLog(@"The same question number appeared!");
} else {
    questionLabel.text = [self nextQuestion];
    [self questionTitleChange];

    NSLog(@"New question made");
    // And add the new number to mutableSet of mutableArray.
    [previousQuestions addObject:[NSNumber numberWithInteger:textNum]];
}

}

这篇关于检查的NSMutableArray包含一个int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:57