Swift - Saving highscore using NSUserDefaults
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")
user2397282
Updated on March 09, 2022Comments
-
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 over 9 yearsDon't use
NSUserDefaults
, that is really not what it designed for, it is not a database. Instead save to a file withNSArchiver
.
-
-
Mike S over 9 yearsI think that if statement should be something more like:
if let highscore = userDefaults.valueForKey("highscore") {
-
Catfish_Man over 9 yearsYou probably want objectForKey rather than valueForKey. The latter goes through Key-Value Coding and may have unintended behaviors.
-
Suragch over 8 yearsAccording to this article, you shouldn't use synchronize in iOS 8 and later.
-
Suragch over 8 yearsAlso about syncronize, see this answer: stackoverflow.com/a/25590044/3681880
-
jose920405 over 8 yearssyncronize it is only necessary when the user actually can not wait to be done automatically.
-
Dashrath over 8 yearsHow 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 almost 8 yearshello 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 almost 8 yearsif (userDefaults.valueForKey("highscore") == nil) { print("nil") } else { print("not nil") }
-
Ashok R over 7 yearsThanks @beef. Initially edited your answer but community suggested to write it as separate answer.
-
Ashok R over 7 yearscan some body explain why it is downvoted. so i can improve myself.
-
rmaddy almost 7 yearsDo not use
UserDefaults value(forKey:)
to read theInt
. UseUserDefaults integer(forKey:)
. Never use KVC unless you have a clear and specific reason to. -
rmaddy almost 7 yearsWhy 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 ofNSUserDefaults
). -
rmaddy almost 7 yearsDo not create your own instance of
NSUserDefaults
. UseNSUserDefaults.standardUserDefaults()
. -
Mithra Singam almost 6 yearsany reason for down voting?
-
Liam Bolling over 5 yearsI think this was down-voted because you don't need to store the variables for these functions.