user2397282
user2397282

Reputation: 3808

Swift - Saving highscore using NSUserDefaults

I'm using Swift to make a game. I want to save the users high score using NSUserDefaults. I know how to create a new NSUserDefaults variable in my AppDelegate file:

let highscore: NSUserDefaults = NSUserDefaults.standardUserDefaults()

But how do I set/get this in my view controllers?

Upvotes: 15

Views: 29053

Answers (5)

Mithra Singam
Mithra Singam

Reputation: 2091

Swift 5

Set Value

UserDefaults.standard.set("TEST", forKey: "Key") //setString

Retrieve

UserDefaults.standard.string(forKey: "Key") //getString

Remove

UserDefaults.standard.removeObject(forKey: "Key")

Upvotes: 3

Ashok R
Ashok R

Reputation: 20766

In Swift

let highScore = 1000
let userDefults = UserDefaults.standard //returns shared defaults object.

Saving:

userDefults.set(highScore, forKey: "highScore") //Sets the value of the specified default key to the specified integer value.

retrieving:

if let highScore = userDefults.value(forKey: "highScore") { //Returns the integer value associated with the specified key.
        //do something here when a highscore exists
    } else {
        //no highscore exists
}

Upvotes: 17

beeef
beeef

Reputation: 2702

At first, NSUserDefaults is a dictionary (NSDictionary I think). Every app has its own user defaults, so you cannot access the user defaults from any other app.

If the user (the one who plays your game) makes a new highscore, you have to save that highscore like this:

let highscore = 1000
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setValue(highscore, forKey: "highscore")
userDefaults.synchronize() // don't forget this!!!!

Then, when you want to get the best highscore the user made, 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
}

Upvotes: 37

You can use below piece of code:

// Your score var

var score:Int = 0

//save

score = NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "score")

// load without starting value nil problems

if NSUserDefaults.standardUserDefaults().setIntergerForKey:("score") != nil {

score = NSUserDefaults.standardUserDefaults().setIntergerForKey:("score")

}

Upvotes: -2

jigar parmar
jigar parmar

Reputation: 29

var defaults=NSUserDefaults()
var highscore=defaults.integerForKey("highscore")

if(Score>highscore)
{
    defaults.setInteger(Score, forKey: "highscore")
}
var highscoreshow=defaults.integerForKey("highscore")

lblHighScore.text="\(highscoreshow)
println("hhScore reported: \(lblHighScore.text)")
lblPlayScore.text="\(Score)"
println("play reported: \(lblPlayScore.text)")

Upvotes: 0

Related Questions