[Solved] NSUserDefaults for high score is not working on iOS 8 Simulator?


Let’s step through your code.

First, you overwrite whatever the high score was with 0:

//To save highest score
let highscore = 0
let userDefaults = NSUserDefaults.standardUserDefaults()
NSUserDefaults.standardUserDefaults().setObject(highscore, forKey: "highscore")
NSUserDefaults.standardUserDefaults().synchronize()

Then, you’re checking if “highscore” is in the defaults:

if let highscore: AnyObject = userDefaults.valueForKey("highscore") {

A few notes:

  • This will always be true because you just set it
  • You should be using objectForKey(_:), not valueForKey(_:)
  • But really you should be using integerForKey(_:) not objectForKey(_:), since highscore is always an Int.
  • You can delete : AnyObject because objectForKey(_:) returns AnyObject?

Then, we go into the code:

    NSUserDefaults.standardUserDefaults().setObject(score, forKey: "highscore")
    NSUserDefaults.standardUserDefaults().synchronize()

You are now overwriting the 0 score you just added earlier with whatever score is.

Finally, your else block, which will never get called, sets highscore, even though you just did that before the if condition.

}
else {
    NSUserDefaults.standardUserDefaults().setObject(highscore, forKey: "highscore")
    NSUserDefaults.standardUserDefaults().synchronize()
}

It’s not clear from your code what you want to do, but you did say this in your question:

I can’t find whats wrong with the replacing of the highScore with score if it is higher.

Well, for one thing, you’re never checking which one is higher.

I think you might be trying to do this:

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

if score > highscore {
    defaults.setInteger(score, forKey: "highscore")
    defaults.synchronize()
}

0

solved NSUserDefaults for high score is not working on iOS 8 Simulator?