Saving Highscores with Nsuserdefaults

NSUserDefaults - Saving and retrieving High Scores

I guess you forgot to save retrieved highs score to the variable:

let highscore = NSUserDefaults.standardUserDefaults().integerForKey("highscore")

Saving highscore with NSUserDefaults

In the code you gave, you are setting "Highscore" when updating, but are attempting to get the value for "HighScore" (Notice the capital S)

This line:

if (highScoreDefault.valueForKey("HighScore") != nil){

Change it to:

if (highScoreDefault.valueForKey("Highscore") != nil){

Nsuserdefaults highscore saving

Change viewDidLoad to:

override func viewDidLoad() {
super.viewDidLoad()

if let hscore = defaults.valueForKey("highscore") {
highscore = hscore
highScoreResult.text = String(hscore)
}
}

That should load the highscore from the defaults once you're app launches.

How to save a highscore to a game in swift with UserDefaults?

Try this

func saveHighScore() {
UserDefaults.standard.set(score, forKey: "HIGHSCORE")
}


Related Topics



Leave a reply



Submit