UserDefaults的全局数据 - Swift

时间:2017-07-27 19:40:01

标签: swift swift3 nsuserdefaults watchkit

我希望永久存储一个字符串,并使用全局数据在多个接口控制器上访问它。这是我按下按钮时设置String的代码。

  

以下所有代码均位于接口控制器1

UserDefaults.standard.set("yellow", forKey: "newBingoColor")

以下代码位于Awake With Context:

    override func awake(withContext context: Any?) {
    super.awake(withContext: context)

    let newBingoColorObject = UserDefaults.standard.object(forKey: "newBingoColor")

    if let newBingoColor = newBingoColorObject as? String {

        temporaryVars.newBingoColor = newBingoColor as! String

        print(newBingoColor)
        print(temporaryVars.newBingoColor)

    }

问题是字符串被保存到temporaryVars.newBingoColor并且我可以在Interface Controler 2上看到它,但是当我重新启动程序时,temporaryVars.newBingoColor在接口控制器2上没有打印。如果我尝试在接口控制器1上查看它虽然显示正常吗?

这里有什么不对?

1 个答案:

答案 0 :(得分:-1)

在AppDelegate中,将此行代码添加到applicationDidEnterBackground函数:

UserDefaults.standard.synchronize()

并且,在设置键之后添加相同的行:

UserDefaults.standard.set("yellow", forKey: "newBingoColor") UserDefaults.standard.synchronize()