我希望永久存储一个字符串,并使用全局数据在多个接口控制器上访问它。这是我按下按钮时设置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上查看它虽然显示正常吗?
这里有什么不对?
答案 0 :(得分:-1)
在AppDelegate中,将此行代码添加到applicationDidEnterBackground
函数:
UserDefaults.standard.synchronize()
并且,在设置键之后添加相同的行:
UserDefaults.standard.set("yellow", forKey: "newBingoColor")
UserDefaults.standard.synchronize()