Objective C - XCode not recognizing variable outside of if statement(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语句之外的变量
基础教程推荐
- Android:对话框关闭而不调用关闭 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01