Reputation: 107
I am trying to save an integer variable in swift/xcode so that when the user opens the application, the number they are incrementing stays the sames (is saved). So far, no luck with this code. The number always goes back to zero when I relaunch the app. The button below simply increments the smoke variable by 1, I want to save that data.
Thank you for your time.
let defaults = UserDefaults.standard
var smoke = 0
@IBAction func incrementSmoke(_ sender: UIButton) {
smoke+=1
defaults.set(smoke, forKey: "smoke")
numDaysLabel.text = String(defaults.integer(forKey: "smoke"))
}
Upvotes: 0
Views: 1575
Reputation: 10116
In an appropriate spot you should be initializing your smoke
property with the value stored in UserDefaults
. For example, you might want to do this in viewDidLoad
, or you could just do it directly in the initializer where you declare the property.
var smoke = UserDefaults.standard.integer(forKey: "smoke")
@IBAction func incrementSmoke(_ sender: UIButton) {
smoke += 1
UserDefaults.standard.set(smoke, forKey: "smoke")
numDaysLabel.text = String(smoke)
}
Note integer(forKey:)
will return 0
by default if there is no value stored in your UserDefaults
already for that key. If you want to set an initial value for the key, register(defaults:)
.
Note, since your value is supposed to be an integer, you might as well use integer(forKey:)
instead of object(forKey:)
so you don't have to deal with an optional / Any
.
Upvotes: 2
Reputation: 103
You can use this one line of code to get data from UserDefaults
. If there is data then it is returned, or it returns 0.
let smoke = UserDefaults.standard.object(forKey: "smoke") ?? 0
Upvotes: 0
Reputation: 653
Swift 4
Set Value
UserDefaults.standard.set("Value", forKey: "Key") //setString
Get
UserDefaults.standard.string(forKey: "Key") //getString
Remove
UserDefaults.standard.removeObject(forKey: "Key")
In your viewDidLoad
smoke = UserDefaults.standard.string(forKey: "smoke") ?? 0
Then
numDaysLabel.text = "\(smoke)"
Upvotes: 1