Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 目标C-XCode无法识别if语句之外的变量_Objective C_Xcode_Cocos2d Iphone_Scope - Fatal编程技术网

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

Objective c 目标C-XCode无法识别if语句之外的变量,objective-c,xcode,cocos2d-iphone,scope,Objective C,Xcode,Cocos2d Iphone,Scope,尝试使用if语句设置sprite文件名,然后基于该字符串加载适当的文件。看起来我的变量范围有问题,但我不知道是什么问题 这是我的密码: if ([[GameManager sharedGameManager] newHighScore] == TRUE) { NSString *highScoreLabelText = @"label-new-high-score.png" } else { NSString *highScoreLabelText = @"label-high-

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

这是我的密码:

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中声明其他内容以使其余代码使用该变量?

在if-else语句之外声明局部变量这是因为在if

的两个分支中声明了两个独立的内部作用域变量。这两个变量在其范围之外都不可见,因此您将得到一个错误

如果,则应将声明移出
,如下所示:

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

现在,
highScoreLabelText
在您的
if
语句之外可见。

这是正确的,当您尝试在if之外使用它时,它超出了范围,请在前面用
NSString*thistring声明它
然后在if语句中设置值。@MyKuLLSKI在过去的几个月里,我观察到,有很多细节的正确答案比简单的正确答案更受关注;使用代码和大量细节的正确答案会得到更多关注。提供详细信息或修复OP的代码需要时间,因此您通常会比其他人晚发布您的答案,而其他人与您同时发现错误。我不是打字最快的人之一,所以我在这方面相对劣势。当我在我的答案之前看到一个质量相当的答案时,我会删除我的答案,除非我在另一个答案的代码中看到错误。