-2

I want the code to start a var num = 0. Then after every button hit num increases by 1. The problem that I am running into is that when I switch view controllers and come back to this one it starts at 0 again. Num can only starts at 0 one tie when is loaded for the first time. I want to use userdefults to save the number so no matter what the score will always increase.

import UIKit

class ViewController: UIViewController {
    var num = 0
    let defaults = UserDefaults.standard

    @IBAction func press () {
        num += 1
        defaults.set(num, forKey: "num")
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579

2 Answers2

2

You have to initialize num from UserDefaults.

Add this to viewDidLoad:

num = defaults.integer(forKey: "num")

Or simply update your var num = 0 line to:

var num = UserDefaults.standard.integer(forKey: "num")

You can't use your defaults variable in this case.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
-1
  1. Call synchronize() immediately after your set data in user defaults, so it save it.
  2. set already set value back to num in View Will Appear as View Will Appear will be called on Pop to this View from other Screen.

See Code

import UIKit

class ViewController: UIViewController {

    var num = 0
    let defaults = UserDefaults.standard

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        num = defaults.integer(forKey: "num")
        print("Value of number from defaults \(num)")
    }

    @IBAction func press () {
        num += 1
        defaults.set(num, forKey: "num")
        defaults.synchronize()
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Chatar Veer Suthar
  • 15,541
  • 26
  • 90
  • 154
  • No, there is no need to call `synchronize`. It's obsolete. Please read the documentation. And please see [When and why should you use NSUserDefaults's synchronize() method?](https://stackoverflow.com/questions/40808072/when-and-why-should-you-use-nsuserdefaultss-synchronize-method) – rmaddy Jul 08 '18 at 05:21
  • @rmaddy Thanks for correcting me. -synchronize is deprecated and will be marked with the NS_DEPRECATED macro in a future release. I saw now - yet they didn't mark it - I have Xcode Version 9.4.1 (9F2000) Documentation. But its mentioned, they will do mark it as deprecated. Thanks. – Chatar Veer Suthar Jul 08 '18 at 05:24
  • It's never been needed. They are just now getting around to deprecating it. – rmaddy Jul 08 '18 at 05:25