IOS KVO & KVC 模式
一.KVO 模式
key-value observing (观察者模式),即键值监听,分为观察者和被观察对象,当被观察对象中属性发生变化,被观察对象会通过观察者.
OC中,KVO常用方法:
- 注册指定Key路径的监听器 : addObserver: forKeyPath: options: context:
- 删除指定Key路径的监听器 : removeObserver: forKeyPath ,removeObserver: forKeyPath: context:
- 回调监听 : observerValueForKeyPath: ofObject: change: context:
KVO 使用步骤:
- 通过 addObserver: forKeyPath: options: context: 为被观察对象(一般为数据模型),注册监听器
- 重写监听器 observerValueForKeyPath: ofObject: change: context 方法
1 // 被观察对象 2 @interfance Account : NSObject 3 4 @property (nonautomatic, assign) float balance; 5 6 @end 7 8 @implementation Account 9 10 ... 11 12 @end 13 14 // 监听对象 15 @interfance Person : UIViewController 16 { 17 float balance; 18 Account *account; 19 } 20 21 - (Person *) initWithPerson; 22 23 - (void) observerValueForKeyPath: (NSString *) forPath ofObject: (id) object change: (NSDictionary *) change context: (void *) context; 24 25 @end 26 27 @implementation Person 28 29 - (Person *) initWithPerson 30 { 31 [self.account addObserver: self forKeyPath: @"balance" options: 0 context: @"KVO_ACCOUNT_BALANCE"]; 32 } 33 34 - (void) observerValueForKeyPath: (NSString *)forPath foObject: (id) object change: (NSDictionary *) change context: (void *) context 35 { 36 if (context == @"KVO_ACCOUNT_BALANCE" && object == self.account) 37 { 38 39 } 40 } 41 42 @end