Reputation: 689
Im making a game and when the user collects an orb I want it to save in an lael but only once. I got it to save the integer in a label but need help with not letting the the orb be saved more than once. Here is the code Im using:
if firstBody.categoryBitMask == HeroCategory && secondBody.categoryBitMask == OrbCategory {
//saves orbs
UserDefaults().set(UserDefaults().integer(forKey: "saveOrbs")+1, forKey:"saveOrbs")
UserDefaults().integer(forKey: "saveOrbs").description
orbLabel.text = UserDefaults().integer(forKey: "saveOrbs").description
}
Upvotes: 2
Views: 248
Reputation: 547
Try checking the key before setting it like
if UserDefaults.standard.value(forKey: "haveSavedOrb") == nil {
UserDefaults.standard.set(true, forKey: "haveSavedOrb")
UserDefaults.standard.set(orbs + 1, forKey: "saveOrbs")
}
Upvotes: 5
Reputation: 18551
In Swift 3:
To set the value 100
for the key MyInt
UserDefaults.standard.set(100, forKey: "MyInt")
And later to retrieve the value for MyInt
.
let myInt = UserDefaults.standard.integer(forKey: "MyInt")
Upvotes: 0