我有一个程序,当用户按下播放按钮时会播放不同的音频剪辑。要播放音频,信用值必须大于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,并且它不记得我存储的值。
答案 0 :(得分:1)
那是因为您始终将@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
称为操作中的第一件事。您正在这样做:
defaults.set(dataCredit, forKey: "credits")
更新:
要设置功劳的初始值,我建议在AppDelegate-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)"
}
}
方法中进行设置:
didFinishLaunchingWithOptions