Global Data with UserDefaults - Swift

Viewed 422

I want to store a String permanently and access it on multiple Interface Controllers using global data. This is my code for setting the String when a button is pressed.

All code below is on Interface Controller 1

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

This code below is in 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)

    }

The problem is the string is saved to temporaryVars.newBingoColor and I can see it on Interface Controler 2 but when I restart the program, temporaryVars.newBingoColor is printed as nothing on Interface Controller 2. If I try to view it on Interface Controller 1 though it shows up fine?

What is incorrect here?

1 Answers
Related