For some kind of reason, the variable declared in the if condition get’s an unused variable and the variable that’s going to be used later gets the undeclared variable. Why is this happening and what’s the way to fix it.?
NSString *name = [NSString stringWithFormat:@"Josh"];
if ([name isEqualToString:@"Josh"])
{
NSString *greeting = [NSString stringWithFormat:@"Hello Josh"]; //Warning: Unused variable 'greeting'
}
else
{
NSString *greeting = [NSString stringWithFormat:@"Hello %@", name]; //Warning: Unused variable 'greeting'
}
NSLog (@"%@", greeting); //Error: 'greeting' undeclared
You should definitely read about variables scope.
Here’s a proper code: