Search code examples
iosswiftnsuserdefaultsscoring

Why my highscore stopped updating?


I've made a highscore and tested it several hours ago, it worked fine. My best score was 6 and game saved it. But now, I've made a score of 10, then 12 and it still shows me that my highscore is 6. I'm pretty sure I did not touch anything related to that piece of code after I've made it. Here is my highscore:

override func didMoveToView(view: SKView) {
//highscore
var HighScoreDefaults = NSUserDefaults.standardUserDefaults().integerForKey("highscore")

if (score > HighScoreDefaults) {
    NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "highscore")
    NSUserDefaults.standardUserDefaults().synchronize()
}
var showHighscore = NSUserDefaults.standardUserDefaults().integerForKey("highscore")

highScoreText.text = "Highscore : \(showHighscore)"
highScoreText.fontSize = 34
highScoreText.fontColor = SKColor.grayColor()

}

What could go wrong?

EDIT: So I put my code, edited by @trojanfoe in override func update(currentTime: NSTimeInterval) function and it's working again. I honestly don't know what caused that problem, but for those who have same problem that I had – try Update instead of didMoveToView.


Solution

  • Your code looks like it should work, however there have been changes to when NSUserDefaults synchronize actually writes the data to disk (see this SO question).

    Given you know what the new highscore is, you can avoid the issue entirely by using this (slightly more efficient and more obvious) code:

    override func didMoveToView(view: SKView) {
        //highscore
        var highScore = NSUserDefaults.standardUserDefaults().integerForKey("highscore")
    
        if (score > highScore) {
            highScore = score;
            NSUserDefaults.standardUserDefaults().setInteger(highScore, forKey: "highscore")
            NSUserDefaults.standardUserDefaults().synchronize()
        }
    
        highScoreText.text = "Highscore : \(highScore)"
        highScoreText.fontSize = 34
        highScoreText.fontColor = SKColor.grayColor()
    }
    

    (i.e. avoiding the additional reading of NSUserDefaults).