Reputation: 4844
I’ve attempted to add KVO to my NSUserDefaults
to watch for a value changing in Settings. I’ve added a breakpoint to my observeValueForKeyPath:object:change:context
method but it’s never called.
Here’s my code:
override init() {
super.init()
NSUserDefaults.standardUserDefaults().addObserver(self, forKeyPath: UserWantsUbiquityPreferenceKey, options: NSKeyValueObservingOptions.New, context: nil)
}
override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<Void>) {
println("\(keyPath) changed to \(object)")
}
Upvotes: 1
Views: 1194
Reputation: 92409
The following code may help you build your KVO:
import UIKit
//observer's context
private var defaultsContext = 0
class ViewController: UIViewController {
let defaults = NSUserDefaults.standardUserDefaults()
@IBAction func changeDefaults(sender: AnyObject) {
//Toggle myPref value (true/false)
defaults.setBool(!defaults.boolForKey("myPref"), forKey: "myPref")
defaults.synchronize()
}
override func viewDidLoad() {
super.viewDidLoad()
//Add observer
defaults.addObserver(self, forKeyPath: "myPref", options: NSKeyValueObservingOptions(), context: &defaultsContext)
}
//Observe changes
override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<Void>) {
if context == &defaultsContext {
seeUpdate()
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
//React to changes
func seeUpdate() {
println(defaults.boolForKey("myPref"))
}
deinit {
//Remove observer
defaults.removeObserver(self, forKeyPath: "myPref", context: &defaultsContext)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Upvotes: 3