Dan
Dan

Reputation: 3103

Detect changes on NSUserDefaults with suiteName

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

Answers (2)

pkamb
pkamb

Reputation: 34983

Foundation Release Notes for macOS 10.12 and iOS 10

https://developer.apple.com/library/archive/releasenotes/Miscellaneous/RN-Foundation-OSX10.12/index.html

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

karthikPrabhu Alagu
karthikPrabhu Alagu

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

Related Questions