[英]How do I save an integer once in Swift?
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.
我得到了将整数保存在标签中的方法,但是需要帮助,不要让orb被保存多次。 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
}
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")
}
In Swift 3: 在Swift 3中
To set the value 100
for the key MyInt
为键
MyInt
设置值100
UserDefaults.standard.set(100, forKey: "MyInt")
And later to retrieve the value for MyInt
. 然后再获取
MyInt
的值。
let myInt = UserDefaults.standard.integer(forKey: "MyInt")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.