一.概述
KVO,即:Key-Value Observing睡雇,它提供一種機(jī)制,當(dāng)指定的對象的屬性被修改后,則對象就會接受到通知。簡單的說就是每次指定的被觀察的對象的屬性被修改后魔种,KVO就會自動通知相應(yīng)的觀察者了缩麸。
二.使用的步驟
1.注冊仿村,指定被觀察者和觀察的對象
objectToObserve.addObserver(self, forKeyPath: "contentArray", options: .new, context: &myContext)
2.實(shí)現(xiàn)屬性變化的回調(diào)
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &myContext {
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
3.移除觀察
deinit {
objectToObserve.removeObserver(self, forKeyPath: "contentArray", context: &myContext)
}
三.完整的代碼
@objcMembers class MyObjectToObserve: NSObject {
dynamic var contentArray = [String]()
}
private var myContext = 0
class PlaySpeechString: NSObject,AVSpeechSynthesizerDelegate {
static let shared = PlaySpeechString()
var objectToObserve = MyObjectToObserve()
// Make sure the class has only one instance
// Should not init or copy outside
private override init() {
super.init()
objectToObserve.addObserver(self, forKeyPath: "contentArray", options: .new, context: &myContext)
}
override func copy() -> Any {
return self // SingletonClass.shared
}
override func mutableCopy() -> Any {
return self // SingletonClass.shared
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &myContext {
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
deinit {
objectToObserve.removeObserver(self, forKeyPath: "contentArray", context: &myContext)
}
}
注意:
1.被觀察屬性所在的類需要用 @objcMembers 關(guān)鍵字修飾 要不會報(bào)error
fatal error: Could not extract a String from KeyPath
Swift.ReferenceWritableKeyPath
2.被觀察的屬性需要用dynamic修飾,否則也無法觀察到。