目标C'如果没有'陈述

时间:2014-07-09 13:11:36

标签: objective-c if-statement shared

我的代码如下:

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    NSString *article = self.textField_artcile.text;
    int article_int = [article intValue];

    NSString *prim = self.textField_prim.text;
    int prim_int = [prim intValue];

    NSString *part = self.textField__part.text;
    int part_int = [part intValue];

    if (prim_int == 0) {

    int myVal = [[NSString stringWithFormat:@"%d%d",article_int,part_int] intValue];
     //short myVal
    }

    else {

        int myVal = [[NSString stringWithFormat:@"%d%d%d",article_int,prim_int,part_int] intValue];
        //long myVal
         }


    NSLog(@"myVal %d",myVal);  <<<this line returns error 'Use of undeclared identifier 'myVal' 

    [self.view endEditing:YES];

}

预计在编辑结束后,将返回myVal(短一个或长一个)

2 个答案:

答案 0 :(得分:2)

您需要在if / else语句之外声明myVal。否则,其范围仅限于代码的这一部分。

int myVal;
if (prim_int == 0) {
    myVal = [[NSString stringWithFormat:@"%d%d",article_int,part_int] intValue];     
}
else {
    myVal = [[NSString stringWithFormat:@"%d%d%d",article_int,prim_int,part_int] intValue];        
}

答案 1 :(得分:1)

myval变量在ifelse主体内定义,并且仅在该范围内是本地变量。您需要在您使用它的范围内声明变量。