Reputation: 3103
I created appGroups and did set up a NSUserDefaults
using that group. I have a observer for which is not triggered when the value is changed.
let defaults = NSUserDefaults(suiteName: "group.daniesy.text")!
defaults.addObserver(self, forKeyPath: "temp", options: NSKeyValueObservingOptions.New, context: nil)
defaults.setBool(!defaults.boolForKey("temp"), forKey: "temp")
defaults.synchronize()
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
println("changed")
}
However if i ignore the appGroup and use NSUserDefaults.standardUserDefaults()
it works as expected.
Any idea why it's not working?
Upvotes: 14
Views: 5129
Reputation: 34983
Key-Value Observing and NSUserDefaults
In previous releases, KVO could only be used on the instance of NSUserDefaults returned by the +standardUserDefaults method. Additionally, changes from other processes (such as defaults(1), extensions, or other apps in an app group) were ignored by KVO. These limitations have both been corrected. Changes from other processes will be delivered asynchronously on the main queue, and ignore NSKeyValueObservingOptionPrior.
Upvotes: 5
Reputation: 3401
Try adding suitename instead of initializing. Set up an App Group if you want to share the data
let defaults = NSUserDefaults.standardUserDefaults()
defaults.addSuiteNamed("group.daniesy.text")
defaults.addObserver(self, forKeyPath: "temp", options: NSKeyValueObservingOptions.New, context: nil)
defaults.setBool(!defaults.boolForKey("temp"), forKey: "temp")
defaults.synchronize()
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
println("changed")
}
Upvotes: 2