KVO with shared NSUserDefaults in Swift

2020-07-14 05:51发布

I am having issues communicating between my host app and its extensions through communicating NSUserDefaults changes.

I initialized NSUserDefaults using init(suiteName:), added KVO observer using the addObserver(...) method and overrided the method observeValueForKeyPath(...) but the method observeValueForKeyPath(...) is not called when I change the value corresponding to the observing key. It will be greatful if you help me to resolve this.

PS:here suite name is App groups name and NSUserDefaults created using suiteName as group identifier will be inside the private area for app groups.

标签: swift ios7 ios8
2条回答
萌系小妹纸
2楼-- · 2020-07-14 06:01

The short answer is that you can't use KVO or even NSNotificationCenter on NSUserDefaults to communicate changes between an App Extension and the containing App.

There's a great post by Atomic Bird that looks at the ways of coordinating communication. In particular its interesting to look at his analysis of communicating user defaults changes:

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.

So I guess for now a good solution might be to use MMWormhole as they implement the above solution.

Your other option is to use to check the user defaults every time your App becomes active and confirm whether any keys have changed, posting the relevant notifications etc.

Good luck

查看更多
We Are One
3楼-- · 2020-07-14 06:09

Just tested, for iOS version later than 10.0, the KVO of the UserDefatuls works perfect fine across process.

查看更多
登录 后发表回答