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

855 Views Asked by At

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.

2

There are 2 best solutions below

2
On BEST ANSWER

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.

0
On

You could use a singleton. The easiest way to create a singleton is to make the variable you want to share between InterfaceControllers a class/static property.

You can create it like this:

class CommonClass {
    static var mySingleton = true
}

Then access it from your InterfaceControllers like this: CommonClass.mySingleton = false.

You should be cautious when using singletons, since they can be accessed anywhere from your code, so they can be misused to act like global variables, which can have its pitfalls.

Check out this article for more details about singletons.