1

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)")
}
Adam Carter
  • 4,741
  • 5
  • 42
  • 103

1 Answers1

3

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()
    }

}
Imanou Petit
  • 89,880
  • 29
  • 256
  • 218
  • `init(suiteName)` initializer of `NSUserDefaults` used to initialize `NSUserDefault` and done the same code, Its not even executing `observeValueForKeyPath(...)` method in device. do you have any idea about it? – Rafeek Feb 26 '15 at 07:03