I need to share a string with all the pages from the first page. I was trying to do this with didDeactive() but its not working. Is it possible to even do this?
1 Answers
It's a bit difficult to tell what you are really trying to do, so I'm going to infer a bit. I "think" you are trying to set some shared value from the first page and be able to use that value in other pages. If that's the case, then you could do something like the following:
class SharedData {
var value1 = "some initial value"
var value2 = "some other initial value"
class var sharedInstance: SharedData {
struct Singleton { static let instance = SharedData() }
return Singleton.instance
}
private init() {
// No-op
}
}
class Page1InterfaceController: WKInterfaceController {
func buttonTapped() {
SharedData.sharedInstance.value1 = "Something new that the others care about"
}
}
class Page2InterfaceController: WKInterfaceController {
@IBOutlet var label: WKInterfaceLabel!
override func willActivate() {
super.willActivate()
self.label.setText(SharedData.sharedInstance.value1)
}
}
The SharedData
object is a singleton class that is a global object. Anyone can access it from anywhere. In the small example I provided, the Page1InterfaceController
is handling a buttonTapped
event and changing the value
property of the SharedData
instance to a new value. Then, when swiping to Page2InterfaceController
, the new value is being displayed in label
.
This is a super simple example of sharing data between objects. Hopefully that helps get you moving in the right direction.

- 16,575
- 7
- 58
- 66
-
Thanks, cnoon. I ended up using a singleton pattern. Since my data had to be reload for a button event I also used reloadRootControllersWithNames(names,contexts) for the reloading case. – Vinay Mar 14 '15 at 09:56
-
I also found a thread safe implementation for a singleton using Swift at this link http://code.martinrue.com/posts/the-singleton-pattern-in-swift – Vinay Mar 14 '15 at 09:57
-
Hi @Vinay, my approach is thread-safe as well. See [this](http://stackoverflow.com/a/24147830/1342462) thread that has a much better take on Swift singletons. – cnoon Mar 14 '15 at 17:13