我试图将 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)")
}
最佳答案
以下代码可以帮助您构建 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()
}
}
关于swift - 将 KVO 添加到设置包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26007382/