Search code examples
swiftnsuserdefaults

I tried using UserDefaults for a score not to reset to zero every time it opens but it doesn't work


I am trying to create an in-app currency system in my game. To do this I tried using UserDefaults in order for said currency to not reset to zero every time I close the app and reopen or switch to a different viewController and switch back. However, it doesn't seem to work. Can someone please tell me what I'm doing wrong?

Here is my code:

var notesScore = 0

@IBAction func IncreaseNotes(_ sender: UIButton)
{
    notesScore = notesScore + 1
    notesLabel.text = String(notesScore)
}

override func viewDidLoad()
{
    super.viewDidLoad()

    view.backgroundColor = colors.themeBlue
    notesLabel.textColor = colors.white

    var notesScoreDefault = UserDefaults.standard

    if (notesScoreDefault.value(forKey: "notesScore")  != nil)
    {
        notesScore = notesScoreDefault.value(forKey: "notesScore") as! NSInteger
        notesLabel.text = NSString(format: "Notes: %i", notesScore) as String
    }

Solution

  • You should store score when it is being changed. For example, when you are increasing the score, you can store that into userdefaults.

    @IBAction func IncreaseNotes(_ sender: UIButton) {
        notesScore = notesScore + 1
        notesLabel.text = String(notesScore)
        // Saving score.
        UserDefaults.standard.set(self.notesScore, forKey: "notesScore")
    }
    

    Now in viewDidLoad, you can retrieve that score as below,

    let score = UserDefaults.standard.integer(forKey: "notesScore")
    notesLabel.text = String(score)