将KVO添加到“设置”包中

时间:2014-09-24 02:01:52

标签: swift nsuserdefaults key-value-observing

我尝试将KVO添加到NSUserDefaults以观察“设置”中的值更改。我已经为我的observeValueForKeyPath:object:change:context方法添加了一个断点,但它从未被调用过。

这是我的代码:

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

1 个答案:

答案 0 :(得分:3)

以下代码可帮助您构建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()
    }

}