首页 > 解决方案 > I am trying to save an SKLabelNode which is the highscore label but it doesn't work. Also tried UserDefaults

问题描述

I am trying to save high sore in the form of sklabelnode using UserDefaults but it doesn't work. Every time I close and open the app the highscore is gone.

I have tried UserDefaults.

func afterCollision(){

    let highScore = "highScore"
    if gameSettings.highScore < score{
        gameSettings.highScore = score
        let defaults = UserDefaults.standard
        defaults.synchronize()
        defaults.integer(forKey: highScore)
       //I tried using this. 

    }

I expected the highscore to be saved but it is lost after I restart the app.

标签: swift

解决方案


您的代码不会尝试在 UserDefaults 中保存任何内容。您读取一个值并忽略结果。您需要设置新值。

if gameSettings.highScore < score {
    gameSettings.highScore = score
    UserDefaults.standard.set(score, forKey: "highScore")
}

当您的应用启动时,您可以加载高分:

gameSettings.highScore = UserDefaults.standard.integer(forKey: "highScore")

推荐阅读