-1

I have a code as follows:

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

}

It is expected that after end of editing myVal will be returned (short one or long one)

Chris Barlow
  • 3,274
  • 4
  • 31
  • 52
  • 1
    possible duplicate of [Objective-C "if" statements not retaining](http://stackoverflow.com/questions/2706955/objective-c-if-statements-not-retaining) – Wooble Jul 09 '14 at 13:16
  • 1
    Just declare myVal in one place. In each part of your "if" statement you have independent declarations of myVal which will go out of scope at the closing curly brace. Declare myVal before the "if" statement; then it will stay in scope after the statement. – Logicrat Jul 09 '14 at 13:16
  • your `myVal` is not available outside of the scope, which defined it – therefore after any of the branch ran, your _locale_ `myVal` is not available anymore. – holex Jul 09 '14 at 13:20

2 Answers2

2

You need to declare myVal outside of the if/else statement. Otherwise its scope is limited to this section of the code.

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];        
}
Paddyd
  • 1,870
  • 16
  • 26
1

The myval variable are defined inside the if or else bodies, and are local in that scope only. You need to declare the variable outside, in the scope of where you use it.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621