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! :)
Asked
Active
Viewed 110 times
-5
-
1Try searching on google before posting here. – Bista Jul 06 '16 at 06:19
2 Answers
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