1,在写swift的KVO的过程中,其不能监听基本数据类型的属性,若想监听需将其改成NSNumber类型,或其它类型,否则监听的代理方法不走。
2,在写swift的KVO的过程中,被监听的属性必须用“dynamic”修饰,否则监听的代理方法不走。
3,在写swift的KVO的过程中,要保证监听者和被监听者同时存在(考虑到其生命周期)。
4,在写swift的KVO的过程中,要确保最后移除观察者,防止内存泄露。
class MyObjectToObserve: NSObject {
dynamic var myDate = NSDate()
func updateDate() {
myDate = NSDate()
}
}
private var myContext = 0
class MyObserver: NSObject {
var objectToObserve = MyObjectToObserve()
override init() {
super.init()
objectToObserve.addObserver(self, forKeyPath: "myDate", options: .New, context: &myContext)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &myContext {
if let newValue = change?[NSKeyValueChangeNewKey] {
print("Date changed: \(newValue)")
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
deinit {
objectToObserve.removeObserver(self, forKeyPath: "myDate", context: &myContext)
}
}
属性观察器
Swift 中可以为一个属性设置属性观察器,可以说是内建的 KVO 观察,只不过只限于对自身属性的观察。看起来像这个样子:
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
属性观察器只在在初始化完成后触发,而且不限于 NSObject 的子类,Swift 中所有的 Class, Struct, Enum 都可以使用。
Swift 内建的Array, Dictionary, Set 等都是值类型,对其内容的修改包括添加,删除,替换元素也会触发属性观察器。