使用UserDefaults保存和检索bool [英] Saving and retrieving a bool with UserDefaults

查看:163
本文介绍了使用UserDefaults保存和检索bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从UISwitch将 bool 值保存到UserDefaults,并在另一个视图中检索它。但是,我尝试过多个教程和堆栈答案,似乎没有工作。

I'm trying to save a bool value to UserDefaults from a UISwitch, and retrieve it in another view. However, I've tried following multiple tutorials and stack answers and none seem to work.

这就是我保存它的方式:

This is how I'm saving it:

class SettingsViewController: UITableViewController {

@IBOutlet weak var soundSwitchOutlet: UISwitch!

@IBAction func soundSwitch(_ sender: UISwitch) {

    UserDefaults.standard.set(soundSwitchOutlet.isOn, forKey: "sound")

}

这就是我试图在另一个视图中检索它的方式:

and this is how I'm trying to retrieve it in another view:

if let savedValue = UserDefaults.standard.bool(forKey: "sound") {
        boolValue = savedValue
    }

//this is inside viewDidLoad and "boolValue" was declared outside viewDidLoad//

出于某种原因,这段代码给了我错误,而且我尝试过的东西都没有。如何将bool保存到UserDefaults并在另一个视图中检索?

For a reason this code is giving me errors and none of the things I've tried have worked. How can I save a bool to UserDefaults and retrieve it in another view?

编辑:我想我修复了第一部分。但是,我检索布尔值的方式似乎完全错误。另外:没有其他的stackExchange答案回应我的要求,至少不是在swift中。

I think I fixed the first part. However, the way I'm retrieving the boolean seems to be totally wrong. Also: No other stackExchange answer responds to what I'm asking, at least not in swift.

推荐答案

正如Leo在注释 bool(forKey 返回非可选 Bool 。如果密钥不存在 false 已退回。

As Leo mentioned in the comments bool(forKey returns a non-optional Bool. If the key does not exist false is returned.

所以它只是

boolValue = UserDefaults.standard.bool(forKey: "sound")

致电<$ c $不需要其他答案中建议的c> synchronize()。框架会定期更新用户默认数据库。

Calling synchronize() as suggested in other answers is not needed. The framework updates the user defaults database periodically.

这篇关于使用UserDefaults保存和检索bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆