本文介绍了目标C - XCode不识别if语句之外的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用if语句设置sprite文件名,然后根据该字符串加载适当的文件。看起来我的变量范围有问题,但我不知道是什么。

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.

这是我的代码:

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标记一个错误,表示highScoreLabelText是一个未声明的标识符,因此不会编译app。我需要在NSString中声明一些东西,以获得其余的代码使用该变量吗?

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?

推荐答案

是因为您在如果的两个分支中声明了两个单独的内部作用域变量。

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.

如果你应该将声明移出 c $ c>,像这样:

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"
}

现在 highScoreLabelText 语句之外是可见的。

Now highScoreLabelText is visible outside of your if statement.

这篇关于目标C - XCode不识别if语句之外的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:56