简体   繁体   English

使用NSUserDefaults(Swift)在ViewController和TableVC之间传递数据

[英]Pass data between ViewController and TableVC with NSUserDefaults (Swift)

How to pass the state of a NSUserDefault between several Classes in Swift ? 如何在Swift几个类之间传递NSUserDefault的状态? In this case I want to pass this state between one TableViewController , where you change the state on the switch, and one initial VC. 在这种情况下,我想在一个TableViewController和一个初始VC之间传递这种状态,在该TableViewController中您更改了开关的状态。 Here is a little model to understand... 这是一个了解的小模型... 在此处输入图片说明

I used this to set the state with the switch: 我用它来设置开关状态:

@IBAction func changeTouchIDState(sender: AnyObject) {

    if TouchIDSwitch.on {

        NSUserDefaults.standardUserDefaults().setBool(true, forKey: "State")

    } else {

        NSUserDefaults.standardUserDefaults().setBool(false, forKey: "State")

    }
}

If the state = true, the initial VC should ask about the Authentication. 如果状态= true,则初始VC应询问身份验证。

Thanks! 谢谢!

Your question need little more explanation, I don't understand why you want to pass the value as you are already storing in NSUserDefaults which you can access in any class of your app. 您的问题需要更多的解释,我不明白为什么要传递值,因为您已经将其存储在NSUserDefaults ,您可以在应用程序的任何class进行访问。

As per my understanding to your problem I'm suggesting the solution: 据我对您的问题的了解,我建议解决方案:

As you already storing State in NSUserDefaults so before presenting initial VC check NSUserDefaults.standardUserDefaults().boolForKey("State") if its true, ask authentication otherwise don't. 由于您已经将State存储在NSUserDefaults中,因此在提供初始VC之前,请检查NSUserDefaults.standardUserDefaults().boolForKey("State")是否为真,否则请进行身份验证。

After setting the bool, you should synchronise: 设置布尔值后,您应该同步:

NSUserDefaults.standardUserDefaults().synchronize()

Then, you can access that value with: 然后,您可以通过以下方式访问该值:

func boolForKey(_ defaultName: String) -> Bool

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

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