Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 260
wazawoo Avatar asked Dec 07 '25 13:12

wazawoo


2 Answers

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.

like image 147
Dávid Pásztor Avatar answered Dec 09 '25 03:12

Dávid Pásztor


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.

like image 29
crgt Avatar answered Dec 09 '25 03:12

crgt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!