尝试使用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的两个分支中声明了两个单独的内部范围变量.这两个变量都不在其范围之外可见,因此您收到错误.
您应该将声明移出if if,如下所示:
NSString *highscoreLabelText; if ([[GameManager sharedGameManager] newHighscore] == TRUE) { highscoreLabelText = @"label-new-high-score.png" } else { highscoreLabelText = @"label-high-score.png" }
现在,在您的if语句之外可以看到highscoreLabelText.