【发布时间】:2021-11-13 13:38:29
【问题描述】:
我正在开发 CountDown Timer 应用程序,如果时间到了,我会设置计时器以设置闹钟。我做了一个设置 VC 来保存用户是否想要启用声音和振动。我正在尝试使用此代码将用户的首选项保存到 userDefaults
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var soundLabel: UILabel!
@IBOutlet weak var vibrationLabel: UILabel!
@IBOutlet weak var soundSwitch: UISwitch!
@IBOutlet weak var vibrationSwitch: UISwitch!
var soundEnabled = true
var vibrationEnabled = true
let userDefaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
soundLabel.text = "Sound Enabled"
soundLabel.textColor = .white
vibrationLabel.text = "Vibration Enabled"
vibrationLabel.textColor = .white
soundSavedSettings()
vibrationSavedSettings()
}
@IBAction func soundSwitchPressed(_ sender: UISwitch) {
if soundEnabled {
soundEnabled = false
soundLabel.text = "Sound Disabled"
} else {
soundEnabled = true
soundLabel.text = "Sound Enabled"
}
userDefaults.set(soundEnabled, forKey: "soundEnabled")
}
@IBAction func vibrationSwtichPressed(_ sender: UISwitch) {
if vibrationEnabled {
vibrationEnabled = false
vibrationLabel.text = "Vibration Disabled"
print("\(vibrationEnabled.description)")
} else {
vibrationEnabled = true
vibrationLabel.text = "Vibration Enabled"
print("\(vibrationEnabled.description)")
}
userDefaults.set(vibrationEnabled, forKey: "vibrationEnabled")
}
func soundSavedSettings() {
soundEnabled = userDefaults.bool(forKey: "soundEnabled")
soundSwitch.isOn = soundEnabled
if soundSwitch.isOn {
soundLabel.text = "Sound Enabled"
} else {
soundLabel.text = "Sound Disabled"
}
}
func vibrationSavedSettings() {
vibrationEnabled = userDefaults.bool(forKey: "vibrationEnabled")
vibrationSwitch.isOn = vibrationEnabled
if vibrationSwitch.isOn {
vibrationLabel.text = "Vibration Enabled"
} else {
vibrationLabel.text = "Vibration Disabled"
}
}
}
但是当我运行应用程序并使用开关将声音或振动设置设置为 false 时,当倒数计时器达到 0 时,应用程序崩溃并给我这个错误:
致命错误:在隐式展开可选值时意外发现 nil
对于 soundSwitch.isOn
.. 不知道该怎么做,因为我尝试了不同的方法,但对我没有任何效果..希望能得到一些帮助..
【问题讨论】:
-
当这段代码第一次运行时,
UserDefaults为这些键存储了nil值……你的soundSavedSettings和vibrationSavedSettings方法在尝试检索保存的值时应该考虑到这一点,因为in:soundEnabled = (userDefaults.bool(forKey: "soundEnabled") ?? true)PS:我还将这些方法重构为具有不同命名约定的方法,如loadPreferences()。您可能还想将保存重构为一种方法savePreferences(),然后调用您的操作 -
@valeCocoa 不,这不是真的。如果密钥不存在,
bool(forKey将返回非可选的false。似乎崩溃与此代码无关。计时器在哪里? -
“应用程序崩溃”在哪里?东德?どこ?
-
然后检查您是否正确连接了 IB 中的视图元素,我假设您这样做了。
-
@vadian 你是对的,问题出在定时器逻辑函数中..虽然解决了..