Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 591
Dănuț Mihai Florian Avatar asked Oct 28 '14 01:10

Dănuț Mihai Florian


Video Answer


2 Answers

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.

like image 149
pkamb Avatar answered Oct 14 '22 23:10

pkamb


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")
}
like image 26
karthikPrabhu Alagu Avatar answered Oct 14 '22 23:10

karthikPrabhu Alagu