0

I am trying to add the ability to send data from iPhone to Watch. I have setup App Groups and everything runs smoothly, but when I try to add an observer to NSUserDefaults in the Watch Extension file, the app always crashes on startup. (And yes, I have verified that the app group name is correct and checked in all Target Capabilities AND all provisioning profiles are up-to-date with App Group enabled)

Code:

override func willActivate() 
{
    super.willActivate()

    NSUserDefaults(suiteName: "my.suite.name")?.addObserver(self, forKeyPath: "phoneSaysHello", options: NSKeyValueObservingOptions.New, context: nil)
}

override func didDeactivate() 
{
    super.didDeactivate()

    // Remove listener for commands sent from phone
    NSUserDefaults(suiteName: "my.suite.name")?.removeObserver(self, forKeyPath: "phoneSaysHello", context: nil)
}

Error:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'An instance 0x7f99534559b0 of class NSUserDefaults was deallocated while key value observers were still registered with it. Current observation info: ( Context: 0x0, Property: 0x7f9953609200> )'

JimmyJammed
  • 9,598
  • 19
  • 79
  • 146

1 Answers1

2

Looks like your NSUserDefaults have gone out scope. Turning userDefaults into an instance variable should stop the exception being thrown.

Rhythmic Fistman
  • 34,352
  • 5
  • 87
  • 159
  • That was an issue when using the 'if let'. I updated to use the NSUserDefaults reference itself, and still get the same crash/error. See updated code. – JimmyJammed Apr 08 '15 at 23:43
  • Try keeping the defaults as an instance variable of your class – Rhythmic Fistman Apr 08 '15 at 23:48
  • Ok changed to instance variable. Doesn't crash, but the observer is never hit when the NSUserDefaults(suiteName: "my.suite.name") is updated by the phone. Does using an instance variable mean that the watch won't recognize when the phone updates it's own instance variable of the app group NSUserDefaults? – JimmyJammed Apr 09 '15 at 01:20
  • That's what I was afraid of: Observing defaults isn't a valid way of communicating between your app and watch extension. For that, have a look at http://stackoverflow.com/q/27144114/22147 or https://github.com/mutualmobile/MMWormhole. However, look on the bright side: your crash is fixed. – Rhythmic Fistman Apr 09 '15 at 01:24