Reputation: 107
I have 4 choices assigned to 4 buttons. One of the choices is correct and it is assigned to the string "correctAnswerString"
The 4 buttons call "action:@selector(submitAnswer:)"
I want to be able to access the string "correctAnswerString" in the "submit Answer" method and compare if the button with the correct answer has been pressed.
I believe this is done by creating an "@interface" in the .h file, but I don't know how to do it.
Many appreciations for the help.
The code is below:
- (void) loadAnswerChoice
{
int correctAnswer = 11;
int incorrectOne = 20;
int incorrectTwo = 5;
int incorrectThree = 8;
correctAnswerString = [NSString stringWithFormat:@"%d", correctAnswer]
[button1 setTitle:[NSString stringWithFormat:@"%d", incorrectOne] forState:UIControlStateNormal];
[button1 addTarget:self action:@selector(submitAnswer:) forControlEvents:UIControlEventTouchUpInside];
[button2 setTitle:[NSString stringWithFormat:@"%d", correctAnswer] forState:UIControlStateNormal];
[button2 addTarget:self action:@selector(submitAnswer:) forControlEvents:UIControlEventTouchUpInside];
[button3 setTitle:[NSString stringWithFormat:@"%d", incorrectTwo] forState:UIControlStateNormal];
[button3 addTarget:self action:@selector(submitAnswer:) forControlEvents:UIControlEventTouchUpInside];
[button4 setTitle:[NSString stringWithFormat:@"%d", incorrectThree] forState:UIControlStateNormal];
[button4 addTarget:self action:@selector(submitAnswer:) forControlEvents:UIControlEventTouchUpInside];
}
- (IBAction)submitAnswer:sender
{
NSString *answer = [sender titleLabel].text;
/*
if ([answer == correctAnswerStr]) {
//do something
}
else
{
//do something else
}
*/
[self performSelector:@selector(loadAnswerChoice) withObject:nil afterDelay:1];
}
Upvotes: 0
Views: 467
Reputation: 39306
No use clicking to only compare again. Why not tie @selector(handleCorrectAnswer:) action to the correct button and @selector(handleIncorrectAnswer:) action to the others? At that point in your code, you know which is the correct one and which ones aren't. You should need to figure that out again in another function.
Also, I assume you're doing a trivial learning exercise. If this was a real app, you would want to externalize the questions and answer as data (file, db etc...) and the code to handle it would be generic. Your code above is pretty hard coded but that's fine if it's just a learning experiment.
Also, you asked about the @interface in header (.h). That's where you define the interface (method and property definitions) for the class. In my suggestion, that means you would add:
@interface MyClass
- (IBAction)handleCorrectAnswer:(id)sender;
- (IBAction)handleIncorrectAnswer:(id)sender;
Then you would implement in your .m
Upvotes: 2