swiftvariablesapple-watchwatchoswkinterfacecontroller

How can I share variables between multiple interface controllers in a paged-based interface on watchOS


I have multiple interface controllers that are both open at the same time in a paged-based format. I need to share information between these interface controllers.

For my use case, I cannot force the user to one of the other interface controllers (by initiating a segue), so the those solutions will not work for me. I need to be able to change some variables in either controller, and access those variables in either controller.

I tried directly setting a variable in an interface controller that is not currently visible in this way:

InterfaceController2().variable = false

But, this didn't work (as expected) since this is not accessing the currently instantiated instance of that interface controller.

I am considering some sort of global variable situation, or storing preferences in UserDefaults, but I feel like there must be a better way.


Solution

  • Best option: If your controllers have a common parent, you could use delegate methods to pass/retrieve values from the common parent.

    Alt: You could create a shared instance that stores your values and your controllers can update/retrieve the value from there.

    Final option: It's a little gross, but you could use NSNotificationCenter. (a) add observers in all of your controllers, (b) post notifications whenever a value updates. And then (c) update the local values in your controllers within the notification handlers.