Haden Yo Haden Yo - 4 months ago 27
Swift Question

NSUserDefaults valueForKey error

I am trying to save a highscore in a simple game. I am new to swift 2 and not sure what I am doing wrong. i am getting the error that "Value of type 'int' has no member for 'valueForKey'. Here is my code as of my last unsuccesful attempt.

var highScoreDefault = NSUserDefaults.standardUserDefaults()

if(highScoreDefault.valueForKey("highScore") != nil){
highScore = highScore.valueForKey("highScore") as NSInteger! //error here
}


newFunc
score += 1
if (score > highScore){
highScore = score
var highScoreDefault = NSUserDefaults.standardUserDefaults()
highScoreDefault.setValue(highScore, forKey: "highScore")
highScoreDefault.synchronize()
}
highscoreLbl.text = "\(highScore)"

Answer

Its very simple to set value in NSUserDefault

NSUserDefaults.standardUserDefaults().setInteger(yourScore, forKey: "highScore")
NSUserDefaults.standardUserDefaults().synchronize()
Comments