iosswiftapple-watchwkinterfacelabel

Swift WKInterfaceLabel IBOutlet Freezes Watchkit App at Startup


I am trying to make a simple example of a watch app: a label and a button. Press the button and the text of the label should change.

@IBOutlet var myLabel: WKInterfaceLabel!
@IBOutlet var myButton: WKInterfaceButton!

The following code results in an endless spinning wheel when I run the app in the simulator as shown in the screenshot:

@IBAction func sampleFunc() {
        myLabel.setText("hello world")
        myButton.setTitle("hermes")
}

enter image description here

Keep in mind. The app never gets to load. I never get to see the button or label. It just stays stuck on this spinning white wheel of dots.

But if I take the exact same code and simply comment out the label, the watch app loads and runs fine.

@IBAction func sampleFunc() {
        //myLabel.setText("hello world")
        myButton.setTitle("hermes")
}

Results in:

enter image description here

And if I click the button, it changes to "hermes" as intended:

enter image description here

Why on earth would this happen? I have been sitting here for four solid hours trying to figure this out. The label is connected as an IBOutlet. I have cleaned the project. I have shut down XCode, restarted my entire computer. I have made a second project from scratch. All the same. Why can't I simply leave this label uncommented? Why does the app never load if the label is uncommented in the action of the button? Extra info: Even if I place the uncommented label elsewhere, such as in the willActivate() method, it behaves the same way with the app never loading.


Solution

  • Nice! After several hours of determined effort on this, just the process of posting the question on StackOverflow helped me to notice the answer. I noticed it out of the corner of my eye in a couple of examples, but never thought it actually mattered. I am speaking of "weak." The answer is simply that the WKInterfaceLabel label has to be weak. Whereas I had been declaring the var like this:

    @IBOutlet var myLabel: WKInterfaceLabel!
    

    I actually needed to be doing this (notice the 'weak'):

    @IBOutlet weak var myLabel: WKInterfaceLabel!
    

    I happened to see it pretty close to the top of this Apple Swift documentation page as a Swift example.

    When I tried it, it worked!