NSUserDefaults - Saving and retrieving High Scores
I guess you forgot to save retrieved highs score to the variable:
let highscore = NSUserDefaults.standardUserDefaults().integerForKey("highscore")
Saving highscore with NSUserDefaults
In the code you gave, you are setting "Highscore" when updating, but are attempting to get the value for "HighScore" (Notice the capital S)
This line:
if (highScoreDefault.valueForKey("HighScore") != nil){
Change it to:
if (highScoreDefault.valueForKey("Highscore") != nil){
Nsuserdefaults highscore saving
Change viewDidLoad to:
override func viewDidLoad() {
super.viewDidLoad()
if let hscore = defaults.valueForKey("highscore") {
highscore = hscore
highScoreResult.text = String(hscore)
}
}
That should load the highscore from the defaults once you're app launches.
How to save a highscore to a game in swift with UserDefaults?
Try this
func saveHighScore() {
UserDefaults.standard.set(score, forKey: "HIGHSCORE")
}
Related Topics
Swift:Difference in '!' and '' in Swift
Dyld: Library Not Loaded, App Requires Afnetworking 2.0.0 But Provides Version 1.0.0
Recursion Over a Swift Sliceable
Swift Optional Type: How .None == Nil Works
Cannot Use Tabview on Swiftui, Watchos
How to Tell If a Symbolic Link Exists at a Certain Path
Nstableview Get Indexpath Having the Cell
Play Segment of Avaudiopcmbuffer
Swift, for Some Uiviews to Their Overall Controller When Clicked
Moving Keyboard When Editing Multiple Textfields with Constraints Swift
What Are the Fundamental Differences Between Set and Didset
Why Is Casting a Struct to Anyobject Not a Compile Error in Swift
Stack Overflow When Defining Subscript on Ckrecord in Swift
Navigationlink Is Grayed Out and Does Not Perform Any Action