iOS WatchKit - 将键值观察器添加到 NSUserDefaults 崩溃

iOS WatchKit - Adding Key Value Observer to NSUserDefaults crashes

我正在尝试添加从 iPhone 向 Watch 发送数据的功能。 我已经设置了应用程序组并且一切运行顺利,但是当我尝试将观察者添加到 Watch Extension 文件中的 NSUserDefaults 时,应用程序总是在启动时崩溃。 (是的,我已验证应用组名称正确并检查了所有目标功能并且所有配置文件都是最新的并启用了应用组)

代码:

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

错误:

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

看起来你的 NSUserDefaults 超出了范围。将 userDefaults 转换为实例变量应该会停止抛出异常。