我有一个程序可以在用户按下播放按钮时播放不同的音频剪辑。对于要播放的音频,信用值必须大于 1。我尝试如下使用 UserDefaults,但它似乎每次都在重置。
class ViewController: UIViewController,.....
var dataCredit = 3
....
@IBAction func playsound(_ sender: Any) {
defaults.set(dataCredit, forKey: "credits")
credit = defaults.integer(forKey: "credits")
if credit > 0 {
feedLabel.text = "you have credits)"
dataCredit = dataCredit - 1
defaults.set(dataCredit, forKey: "credits")
dataCredit = defaults.integer(forKey: "credits")
} else if credit == 0 {
feedLabel.text = "you dont have Credit\(startCredit)"
}
这是我目前拥有的。每次我重新启动应用程序时,dataCredit 都会回到 3,并且它不会记住我存储的值。
最佳答案
那是因为您总是调用 defaults.set(dataCredit, forKey: "credits")
作为操作中的第一件事。你是这样做的:
class ViewController: UIViewController,.....
....
@IBAction func playsound(_ sender: Any) {
if let credit = defaults.integer(forKey: "credits"), credit > 0 {
feedLabel.text = "you have credits)"
dataCredit = dataCredit - 1
defaults.set(dataCredit, forKey: "credits")
dataCredit = defaults.integer(forKey: "credits")
} else if credit == 0 {
feedLabel.text = "you dont have Credit\(startCredit)"
}
}
更新:
要为积分设置初始值,我建议在 AppDelegate - didFinishLaunchingWithOptions
方法中进行:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// ...
UserDefaults.standard.register(defaults: ["credits" : 3])
// ...
return true
}
关于swift - UserDefaults 在新发布时重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54867621/