简体   繁体   English

使用UserDefaults保存和检索布尔值

[英]Saving and retrieving a bool with UserDefaults

I'm trying to save a bool value to UserDefaults from a UISwitch, and retrieve it in another view. 我正在尝试从UISwitch将布尔值保存到UserDefaults,并在另一个视图中检索它。 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//

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? 如何将布尔值保存到UserDefaults并在另一个视图中检索它?

Edit: 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. 另外:没有其他stackExchange答案可以响应我的要求,至少不能迅速做出响应。

As Leo mentioned in the comments bool(forKey returns a non-optional Bool . If the key does not exist false is returned. 正如Leo在评论中提到的那样, bool(forKey返回一个非可选的Bool 。如果键不存在,则返回false

So it's simply 所以这很简单

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

Calling synchronize() as suggested in other answers is not needed. 不需要按照其他答案中的建议调用synchronize() The framework updates the user defaults database periodically. 框架会定期更新用户默认数据库。

Do it like this. 像这样做。

In your first view controller . 在您的first view controller

  • create an IBoutlet connection to your UISwitch 创建到您的UISwitchIBoutlet连接

  • And then the action for your UISwitch . 然后执行UISwitch的操作。 so in the end, your first view controller should look like this. 所以最后,您的first view controller应如下所示。

import UIKit 导入UIKit

class FirstViewController: UIViewController {


    @IBOutlet weak var myswitch: UISwitch! // Outlet connection to your UISwitch (just control+ drag  it to your controller)




    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

    @IBAction func myswitchAction(_ sender: Any) { // Action for your UISwitch

        var myswitctBool : Bool = false // create a local variable that holds your bool value. assume that in the beginning your switch is offed and the boolean value is `false`

        if myswitch.isOn == true { // when user turn it on then set the value to `true`
            myswitctBool = true
        }
        else { // else set the value to false
            myswitctBool = false
        }


        // finally set the value to user default like this
        UserDefaults.standard.set(myswitctBool, forKey: "mySwitch")
        //UserDefaults.standard.synchronize() - this is not necessary with iOS 8 and later.


    }

}

End of the first view controller 第一个视图控制器的结尾

Now in your second view controller 现在在第二个视图控制器中

  • you can get the value of userdefault , which you set in first view controller . 您可以获得在first view controller设置的userdefault的值。 I put it in the viewdidload method to show you how it works. 我将其放在viewdidload方法中,向您展示其工作方式。

import UIKit 导入UIKit

class SecondViewController: UIViewController {

        override func viewDidLoad() {
            super.viewDidLoad()


            let myswitchBoolValuefromFirstVc : Bool = UserDefaults.standard.bool(forKey: "mySwitch")// this is how you retrieve the bool value


            // to see the value, just print those with conditions. you can use those for your things.
            if myswitchBoolValuefromFirstVc == true {
                print("true")
            }
            else {
                print("false")
            }


        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()

        }




    }

Hope this will help to you. 希望这对您有帮助。 good luck 祝好运

Use this line of code: 使用以下代码行:

@IBAction func soundSwitch(_ sender: UISwitch) {
    UserDefaults.standard.set(soundSwitchOutlet.isOn, forKey: "sound")
}

insteadof : 代替 :

@IBAction func soundSwitch(_ sender: UISwitch) {
    UserDefaults.standard.set(soundSwitchOutlet, forKey: "sound")
}

Try this: 尝试这个:

@IBAction func soundSwitchs(_ sender: Any) 
{
    UserDefaults.standard.set(soundSwitchOutlet.isOn, forKey: "sound")
    UserDefaults.standard.synchronize() 
}

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM