iOS WatchKit - Adding Key Value Observer to NSUserDefaults crashes

倖福魔咒の 提交于 2019-12-13 04:27:38

问题


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> )'


回答1:


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



来源:https://stackoverflow.com/questions/29526777/ios-watchkit-adding-key-value-observer-to-nsuserdefaults-crashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!