-5

I am searching for an efficient way to store a "high score" integer in this simple game I am building with Swift in iOS. I want it to keep track of it even if the player shuts down the app, closes it, and restarts it. How should I use the NSUserDefaults function to save this data? Thanks in advance! :)

gentiane
  • 6,715
  • 3
  • 23
  • 34
jj_hennessy
  • 55
  • 1
  • 6

2 Answers2

0
//TO SAVE INTO USER DEFAULT
NSUserDefaults.standardUserDefaults().setInteger(1234, forKey: "highScore")
//TO RETRIEVE FROM USER DEFAULT
var highScore = NSUserDefaults.standardUserDefaults().integerForKey("highScore")
Sandeep Ahuja
  • 931
  • 6
  • 17
0

Save that highscore like this:

 let highscore = 20
        let userDefaults = NSUserDefaults.standardUserDefaults()
        userDefaults.setValue(highscore, forKey: "highscore")
        userDefaults.synchronize() // it is not necessary

When you want to get the info, you have to "read" the highscore from the dictionary like this:

if let highscore = userDefaults.valueForKey("highscore") {
    // do something here when a highscore exists
}
else {
    // no highscore exists
}
Tarvo Mäesepp
  • 4,477
  • 3
  • 44
  • 92