Swift - Saving highscore using NSUserDefaults

28,659

Solution 1

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
}

Solution 2

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
}

Solution 3

Swift 5

Set Value

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

Retrieve

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

Remove

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

Share:
28,659
user2397282
Author by

user2397282

Updated on March 09, 2022

Comments

  • user2397282
    user2397282 about 2 years

    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?

    • zaph
      zaph over 9 years
      Don't use NSUserDefaults, that is really not what it designed for, it is not a database. Instead save to a file with NSArchiver.
  • Mike S
    Mike S over 9 years
    I think that if statement should be something more like: if let highscore = userDefaults.valueForKey("highscore") {
  • Catfish_Man
    Catfish_Man over 9 years
    You probably want objectForKey rather than valueForKey. The latter goes through Key-Value Coding and may have unintended behaviors.
  • Suragch
    Suragch over 8 years
    According to this article, you shouldn't use synchronize in iOS 8 and later.
  • Suragch
    Suragch over 8 years
    Also about syncronize, see this answer: stackoverflow.com/a/25590044/3681880
  • jose920405
    jose920405 over 8 years
    syncronize it is only necessary when the user actually can not wait to be done automatically.
  • Dashrath
    Dashrath over 8 years
    How do I access these values in some other controller ( ex : I save user defaults in LoginController.swift and later need to use those on ProfileController.swift ) ? and are these values persistent event after app is closed and relaunched by user ?
  • Akash Raghani
    Akash Raghani almost 8 years
    hello Dashrath you have to check in your next view controller what ever function you want to use from given below code please set formate of code because this is comment thatsy not set properly... hope this help you
  • Akash Raghani
    Akash Raghani almost 8 years
    if (userDefaults.valueForKey("highscore") == nil) { print("nil") } else { print("not nil") }
  • Ashok R
    Ashok R over 7 years
    Thanks @beef. Initially edited your answer but community suggested to write it as separate answer.
  • Ashok R
    Ashok R over 7 years
    can some body explain why it is downvoted. so i can improve myself.
  • rmaddy
    rmaddy almost 7 years
    Do not use UserDefaults value(forKey:) to read the Int. Use UserDefaults integer(forKey:). Never use KVC unless you have a clear and specific reason to.
  • rmaddy
    rmaddy almost 7 years
    Why is this answer so popular? Just about every line is wrong. It's using the wrong methods. Don't use KVC unless you have a clear and specific reason to. And you do not need to call synchronize. The answer by jigar is using the proper Swift 2 API (except for creating a new instance of NSUserDefaults).
  • rmaddy
    rmaddy almost 7 years
    Do not create your own instance of NSUserDefaults. Use NSUserDefaults.standardUserDefaults().
  • Mithra Singam
    Mithra Singam almost 6 years
    any reason for down voting?
  • Liam Bolling
    Liam Bolling over 5 years
    I think this was down-voted because you don't need to store the variables for these functions.