iOS WatchKit-将键值观察器添加到NSUserDefaults会崩溃 [英] iOS WatchKit - Adding Key Value Observer to NSUserDefaults crashes

查看:103
本文介绍了iOS WatchKit-将键值观察器添加到NSUserDefaults会崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

代码:

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

错误:

***由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'实例 当键值释放时,类NSUserDefaults的0x7f99534559b0被释放了 观察者仍在注册.当前观察信息: ( 上下文:0x0,属性:0x7f9953609200>)'

*** 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转换为实例变量应停止引发异常.

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

这篇关于iOS WatchKit-将键值观察器添加到NSUserDefaults会崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆