iOS在两个方法之间传递一个string

我有4个选项分配给4个button。 其中一个选项是正确的,它被分配给string“correctAnswerString”

4个button调用“action:@selector(submitAnswer :)”

我希望能够访问“submit Answer”方法中的string“correctAnswerString”,并比较是否按下了正确答案的button。

我相信这是通过在.h文件中创build一个“@interface”来完成的,但我不知道该怎么做。

很多赞赏的帮助。

代码如下:


- (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]; } 

没有用点击来再次比较。 为什么不把@selector(handleCorrectAnswer :)动作绑定到正确的button和@selector(handleIncorrectAnswer :)动作给其他人? 在你的代码中,你知道哪一个是正确的,哪些不是。 你应该需要在另一个函数中再次弄清楚。

另外,我假设你正在做一个微不足道的学习练习。 如果这是一个真正的应用程序,你会想要外部化的问题和答案作为数据(文件,数据库等)和处理它的代码将是通用的。 你上面的代码是相当硬编码的,但如果这只是一个学习实验,那很好。

另外,你问了关于标题(.h)中的@interface。 这就是为类定义接口(方法和属性定义)的地方。 在我的build议中,这意味着你会添加:

 @interface MyClass - (IBAction)handleCorrectAnswer:(id)sender; - (IBAction)handleIncorrectAnswer:(id)sender; 

那么你会在你的.m中实现