Search code examples
iosundeclared-identifier

iOS use of undeclared indentifier after if-else statement


I have this piece of code which plays my mp3 files on my iphone and it works:

if(i == 1) { 
  NSString *url = [[NSBundle mainBundle]pathForResource:@"fart" ofType:@"mp3"];
  player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:url] error:NULL];
  [player play];
} else if(i==2) {
  NSString *url = [[NSBundle mainBundle]pathForResource:@"fart6" ofType:@"mp3"];
  player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:url] error:NULL];
  [player play];  
} else {
  NSString *url = [[NSBundle mainBundle]pathForResource:@"fart7" ofType:@"mp3"];
  player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:url] error:NULL];
  [player play];
}

The only lines that are changing is the NSString *url. When I try to do the below to clean up my code, I get the error of "use of undeclared identifier 'url'".

if(i == 1) { 
  NSString *url = [[NSBundle mainBundle]pathForResource:@"fart" ofType:@"mp3"];      
} else if(i==2) {
  NSString *url = [[NSBundle mainBundle]pathForResource:@"fart6" ofType:@"mp3"];        
} else {
  NSString *url = [[NSBundle mainBundle]pathForResource:@"fart7" ofType:@"mp3"];      
}

player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:url] error:NULL];
[player play];

Why does NSURL not understand that the NSString *url is set from the above if-else statements?


Solution

  • "The scope the variables is limited to the block they are declared".

    Declare url outside before the if-else block. You can still optimize your code to be like this.

    NSString *fileName = @"";
    if (i == 1) fileName =  @"fart";
    else if (i == 2) fileName =  @"fart6";
    else fileName =  @"fart7"; 
    
    NSString *path = [[NSBundle mainBundle]pathForResource:fileName ofType:@"mp3"];
    NSURL *url = [NSURL fileURLWithPath:path];
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
    [player play];