我正在尝试高分视图。我加载得分和高分并比较两者,看看是否应该将得分设置为新的高分。当分数为负数时,它可以正常工作,但是当数字为正数但小于当前高分或大于高分时,似乎将两个数字加在一起。它似乎也从两个中减去1?我不确定发生了什么事。谢谢你的帮助!
高分视图viewDidLoad(视图的唯一代码):
override func viewDidLoad() {
//Load Score
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var score = defaults.valueForKey("Score")?.integerValue ?? 0
defaults.synchronize()
Score = score
//Load Highscore
let SecondDefaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var highscore = SecondDefaults.valueForKey("Highscore")?.integerValue ?? 0
SecondDefaults.synchronize()
Highscore = highscore
//Set Score Text
ScoreString = String(Score)
Scorelabel.text = ScoreString
//Update Highscore if Score is bigger
if Score > Highscore {
//Set Highscore to Score
Highscore += Score
//Save Highscore
let SecondDefaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
SecondDefaults.setObject(Highscore, forKey: "Highscore")
SecondDefaults.synchronize()
//Set Highscore Text
HighscoreString = String(Highscore)
HighscoreLabel.text = HighscoreString
NewHighscoreLabel.text = "New Highscore"
}
//Set Highscore Text if Score is smaller
else if Highscore >= Score {
HighscoreString = String(Highscore)
HighscoreLabel.text = HighscoreString
}
}}
答案 0 :(得分:1)
问题在于此代码:
Highscore += Score
您正在添加HighScore
和Score
,然后分配回HighScore。将其更改为:
Highscore = Score