Objective C - XCode无法识别if语句之外的变量

Objective C - XCode not recognizing variable outside of if statement(Objective C - XCode无法识别if语句之外的变量)

本文介绍了Objective 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 是一个未声明的标识符,因此不会编译应用程序.我是否需要与 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?

推荐答案

这是因为您在 if 的两个分支中声明了两个单独的内部范围变量.这两个变量在其范围之外都不可见,因此您会遇到错误.

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.

你应该把声明移出if,像这样:

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 在您的 if 语句之外可见.

Now highScoreLabelText is visible outside of your if statement.

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

本文标题为:Objective C - XCode无法识别if语句之外的变量

基础教程推荐