Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 738
user2397282 Avatar asked Aug 12 '14 16:08

user2397282


People also ask

How do you save NSUserDefaults in Swift?

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.

What types can you store natively in NSUserDefaults?

Storing Default Objects The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Boolean values, and URLs. These methods are described in Setting Default Values.

What is NSUserDefaults in Swift?

A property list, or NSUserDefaults can store any type of object that can be converted to an NSData object. It would require any custom class to implement that capability, but if it does, that can be stored as an NSData. These are the only types that can be stored directly.

Is NSUserDefaults secure?

Because NSUserDefaults stores all data in an unencrypted . plist file, a curious person could potentially view this data with minimal effort. That means that you should never store any type of sensitive data inside NSUserDefaults.


2 Answers

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
}
like image 113
beeef Avatar answered Sep 27 '22 20:09

beeef


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
}
like image 33
Ashok R Avatar answered Sep 27 '22 20:09

Ashok R