Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - XCode not recognizing variable outside of if statement

Trying to set a sprite filename with an if statement, then load the proper file based on that string. It looks like there's a problem with my variable scope, but I don't know what it is.

Here's my code:

if ([[GameManager sharedGameManager] newHighScore] == TRUE) {
    NSString *highScoreLabelText = @"label-new-high-score.png"
} else {
    NSString *highScoreLabelText = @"label-high-score.png"
}

CCSprite *highScoreLabel = [CCSprite spriteWithSpriteFrameName:highScoreLabelText];
[highScoreLabel setAnchorPoint:ccp(0,0)];
[highScoreLabel setPosition:ccp(20, winSize.height * 0.575f)];
[self addChild:highScoreLabel];

XCode is flagging an error, saying that highScoreLabelText is an undeclared identifier, and thus won't compile the app. Do I need to declare something else along with the NSString to get the rest of the code to work with the variable?

like image 736
Kevin Whitaker Avatar asked Nov 21 '25 10:11

Kevin Whitaker


2 Answers

This is because you declared two separate inner-scope variables in both branches of if. Neither of these two variables is visible outside its scope, so you are getting an error.

You should move the declaration out of if, like this:

NSString *highScoreLabelText;
if ([[GameManager sharedGameManager] newHighScore] == TRUE) {
    highScoreLabelText = @"label-new-high-score.png"
} else {
    highScoreLabelText = @"label-high-score.png"
}

Now highScoreLabelText is visible outside of your if statement.

like image 129
Sergey Kalinichenko Avatar answered Nov 23 '25 22:11

Sergey Kalinichenko


Declare the local variable outside the if-else statement

like image 36
MyKuLLSKI Avatar answered Nov 24 '25 00:11

MyKuLLSKI