15

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?

user2397282
  • 3,798
  • 15
  • 48
  • 94
  • 5
    Don't use `NSUserDefaults`, that is really not what it designed for, it is not a database. Instead save to a file with `NSArchiver`. – zaph Aug 12 '14 at 16:47

5 Answers5

37

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
}
Wyetro
  • 8,439
  • 9
  • 46
  • 64
beeef
  • 2,664
  • 4
  • 17
  • 27
  • 4
    I think that if statement should be something more like: `if let highscore = userDefaults.valueForKey("highscore") {` – Mike S Aug 12 '14 at 17:08
  • 1
    You probably want objectForKey rather than valueForKey. The latter goes through Key-Value Coding and may have unintended behaviors. – Catfish_Man Nov 22 '14 at 10:36
  • 5
    According to [this article](http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/), you shouldn't use synchronize in iOS 8 and later. – Suragch Sep 18 '15 at 01:05
  • Also about syncronize, see this answer: http://stackoverflow.com/a/25590044/3681880 – Suragch Sep 18 '15 at 01:26
  • 2
    syncronize it is only necessary when the user actually can not wait to be done automatically. – jose920405 Oct 09 '15 at 14:01
  • 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 ? – Dashrath Dec 28 '15 at 07:28
  • 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 Jun 16 '16 at 12:15
  • if (userDefaults.valueForKey("highscore") == nil) { print("nil") } else { print("not nil") } – Akash Raghani Jun 16 '16 at 12:15
  • 1
    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 Jul 09 '17 at 15:11
17

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
}
inexcitus
  • 2,471
  • 2
  • 26
  • 41
Ashok R
  • 19,892
  • 8
  • 68
  • 68
  • Thanks @beef. Initially edited your answer but community suggested to write it as separate answer. – Ashok R Sep 14 '16 at 04:15
  • can some body explain why it is downvoted. so i can improve myself. – Ashok R Sep 14 '16 at 04:16
  • 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 Jul 09 '17 at 15:09
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")

Mithra Singam
  • 1,905
  • 20
  • 26
0
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)")
SeniorJD
  • 6,946
  • 4
  • 36
  • 53
  • 1
    Do not create your own instance of `NSUserDefaults`. Use `NSUserDefaults.standardUserDefaults()`. – rmaddy Jul 09 '17 at 15:15
-2

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")

}
brainray
  • 12,512
  • 11
  • 67
  • 116