KVO:(Key-ValueObserving)objective-c中可以使用KVO來監聽屬性改變。(通過設置觀察者來實現)
兩個方法:
1、設置監聽
- (void)observeValueForKeyPath:(nullable NSString*)keyPath ofObject:(nullable id)object change:(nullableNSDictionary<NSString*,id> *)change context:(nullable void*)context;
爲控件要監聽的屬性添加觀察者。
2、響應監聽
- (void)observeValueForKeyPath:(nullable NSString*)keyPath ofObject:(nullable id)object change:(nullableNSDictionary<NSString*,id> *)change context:(nullable void*)context;
重寫該方法,並在其中實現屬性變化後的動作代碼。
3、移除監聽響應(常寫在dealloc方法中)
- (void)removeObserver:(NSObject*)observer forKeyPath:(NSString *)keyPath;
參數分析:
keyPath :要監聽的屬性名
object :屬性發生改變的對象
change :屬性發生的變化