我通过传达NSUserDefaults更改在主机应用程序及其扩展之间进行通信时遇到问题.
我使用init(suiteName :)初始化了NSUserDefaults,使用addObserver(…)方法添加了KVO观察者并覆盖了方法observeValueForKeyPath(…)但是当我更改相应的值时没有调用observeValueForKeyPath(…)方法到观察的关键.如果你帮我解决这个问题会很棒.
PS:此处套件名称是应用程序组名称,使用suiteName创建的NSUserDefaults作为组标识符将位于应用程序组的私有区域内.
简短的回答是,您无法在NSUserDefaults上使用KVO甚至NSNotificationCenter来在App扩展和包含应用程序之间进行通信.
有一个great post by Atomic Bird,它着眼于协调沟通的方式.特别有趣的是,看看他对沟通用户默认值变化的分析:
A possible alternative for app/extension notifications is to use the
Darwin notification center via
CFNotificationCenterGetDarwinNotifyCenter,which actually is a little
bit like NSDistributedNotificationCenter. There’s some discussion of
this by Wade Spires at Apple’s dev forums site.
I say “possible” because I’m not 100% confident of this continuing to
work. In the documentation for this method,Apple notes that
An application has only one Darwin notification center,so this
function returns the same value each time it is called.
So although this is apparently legal,it also sounds a lot like it
violates the philosophy inherent in app extension restrictions,viz,
that they can’t access anything from the hosting app. This is why
[UIApplication sharedApplication] is off limits in extensions. I can’t
help wonder if allowing CFNotificationCenterGetDarwinNotifyCenter is
an oversight that might get “fixed” at some point.
所以我想现在一个好的解决方案可能就是使用MMWormhole来实现上述解决方案.
您的另一个选择是每次应用程序变为活动时检查用户默认值,并确认是否有任何键已更改,发布相关通知等.
祝好运