iOS在两个方法之间传递字符串

时间:2011-12-03 14:13:04

标签: ios string methods nsstring parameter-passing

我有4个选项分配给4个按钮。其中一个选项是正确的,它被分配给字符串“correctAnswerString”

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

我希望能够在“提交答案”方法中访问字符串“correctAnswerString”,并比较是否按下了具有正确答案的按钮。

我相信这是通过在.h文件中创建“@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];
}

1 个答案:

答案 0 :(得分:2)

无需点击即可再次进行比较。为什么不将@selector(handleCorrectAnswer :)动作与正确的按钮和@selector(handleIncorrectAnswer :)动作绑定到其他人?在代码中的那一点,您知道哪个是正确的,哪些不是。你需要在另一个函数中重新计算出来。

另外,我假设你正在进行一项微不足道的学习练习。如果这是一个真正的应用程序,您可能希望将问题外部化并作为数据(文件,数据库等...)回答,并且处理它的代码将是通用的。上面的代码非常难以编码,但如果它只是一个学习实验那就没问题。

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

@interface MyClass

- (IBAction)handleCorrectAnswer:(id)sender;
- (IBAction)handleIncorrectAnswer:(id)sender;

然后你将在你的.m

中实现