2014-09-24 47 views
1

我試圖將KVO添加到我的NSUserDefaults以觀察設置中的值變化。我已經爲我的observeValueForKeyPath:object:change:context方法添加了一個斷點,但它從未被調用過。將KVO添加到設置包

這裏是我的代碼:

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

回答

2

下面的代碼可以幫助你建立你的志願:

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

} 
+0

'的init(suiteName)'NSUserDefaults'的'初始化用於初始化'NSUserDefault'和done相同的代碼,它甚至不執行設備中的'observeValueForKeyPath(...)'方法。你有什麼想法嗎? – Rafeek 2015-02-26 07:03:51