Objective-C中KVO簡單用法

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 :屬性發生的變化

發佈了26 篇原創文章 · 獲贊 7 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章