ios - swift : How to check if UserDefaults exists and if not save a chosen standard value?

标签 ios xcode boolean nsuserdefaults uiswitch

我正在尝试检查 UserDefaults 键是否存在,如果不存在,则将其设置为我选择的标准值,但此处关于堆栈溢出的答案并没有帮助我完成这项工作。

基本上我有几个 UISwitch,一个打开,其余的从一开始就设置为关闭。现在我的问题是,当加载 viewController 并且这些键不存在时,我不知道如何将这些初始状态保存到 UserDefaults 中。

这就是我尝试检查 UISwitch 的 key 是否存在以及是否将其设置为 true 的方式(因为这是我想要的状态),然后再次检查 key 的 bool 是什么并设置 UISwitch对它(这在 viewController 再次打开时非常重要):

func setupSwitches() {
    let defaults = UserDefaults.standard

    //check if the key exists 
    if !defaults.bool(forKey: "parallax") {
        switchParallax.setOn(true, animated: true)
    } 

    //check for the key and set the UISwitch
    if defaults.bool(forKey: "parallax") {
        switchParallax.setOn(true, animated: true)
    } else {
        switchParallax.setOn(false, animated: true)
    } 

}

当用户按下相应的按钮时,我会像这样设置 UserDefaults 键:

@IBAction func switchParallax_tapped(_ sender: UISwitch) {
    let defaults = UserDefaults.standard

    if sender.isOn == true {
        defaults.set(true, forKey: "parallax")
    } else {
        defaults.set(false, forKey: "parallax")
    }
}

这显然是可行的,但问题出在上面的第一段代码中。

首先,我不确定如何检查它是否存在,如果不存在则将其设置为“true”,并且由于该函数称为 setupSwitches(),所以它会在每次显示 viewController 时运行。

所以我不知道是否有更好的方法(例如,由于内存问题)来检查 key 是否存在,如果不存在则将其设置为 true,如果它已经存在则从 UserDefaults 获取 bool 并设置切换到正确的状态。

最佳答案

问题是您无法确定 UserDefaults.standard.bool(forKey: key) 是否存在。 UserDefaults.standard.object(forKey: key) 返回 Any? 因此您可以使用它来测试 nil,例如

extension UserDefaults {

    static func exists(key: String) -> Bool {
        return UserDefaults.standard.object(forKey: key) != nil
    }

}

关于ios - swift : How to check if UserDefaults exists and if not save a chosen standard value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47581644/

相关文章:

xcode - Interface Builder 和 Xcode 集成不起作用

java - 如果可选 boolean 值为真,如何执行操作?

MATLAB:快速反转 boolean 值

ios - 如何以编程方式更改单元格中 UIImageView 中显示的图像?

ios - 核心数据测试 : force external storage on iOS

ios - Xamarin IOS CrossMediaManager 后台视频播放

ios - swift 3 : Background music plays again every time the view controller loads

XCode 热键跳转到顶部和返回

javascript - 循环中的数字测试

ios - 如今,数据密集型 iOS 应用程序中普遍接受的加载模式是什么?