Search code examples
iosuibuttonibactionsender

Getting two sender values instead of one for particular case?


I am having a IBAction for 4 buttons which represent 4 available answers and each time I press a button I read the sender ID, then it figures out if answer is correct and so on.

Now I have a special case, when another button (nothing in common with those 4 buttons) is pressed, it waits for two of these answers, checks if one of them is correct( i know how to do that) and then the program continues running.

So for now, I have :

- (IBAction)answerButtonPressed:(id)sender {
    NSString* answer= [[sender titleLabel] text];

   //checks if answer key is equal to a1 ( which is always the correct answer )
    if([[currentQuestionUsefulVariable valueForKey:@"a1"] isEqualToString:answer] ){

        correctQuestionsCount1 ++;
    }
    //answer is wrong
    else{
        wrongQuestionsCount1 ++;
    }
}

As you see I store the answer string in a variable called answer

And again - All I need is to store two answers and check the two of them when this special button is pressed. I will of course put a boolean variable to indicate when it is pressed and it will do the work.

EDIT: The two answer thing is when I press a specific joker button and it gives the advantage to the user to chose two of four available answers. This is why I need to do that. For any other cases I need only one answer at a time.

Any ideas ?


Solution

  • Well you're going to need an instance variable, the value of which persists throughout the lifetime of the object, and perhaps using a mutable array of the answers is the way forward:

    @interface MyViewController ()
    {
        NSMutableArray *_correctAnswers;
    }
    

    It must be initialised in viewDidLoad (other options are available):

    -(void)viewDidLoad {
        [super viewDidLoad];
        _correctAnswers = [NSMutableArray new];
    }
    

    and then start collecting correct answers into this array:

    - (IBAction)answerButtonPressed:(id)sender {
        NSString* answer= [[sender titleLabel] text];
    
       //checks if answer key is equal to a1 ( which is always the correct answer )
        if([[currentQuestionUsefulVariable valueForKey:@"a1"] isEqualToString:answer] ){
            [_correctAnswers addObject:answer];
        }
        //answer is wrong
        else{
            wrongQuestionsCount1 ++;
        }
    
        if ([_correctAnswers count] == 2) {
            // Do something?  It's not exactly clear what you want to do
            // when 2 correct answers have been given.
        }
    }
    

    Note: you can dump correctQuestionsCount1 as that will be [_correctAnswers count] now. Also you will need to reset the array at some point.

    Note 2: You could also start collecting incorrect answers as well, for some analysis or perhaps to disable that button so the user cannot repeatedly answer the question wrong.