标签:
key-value observing (观察者模式),即键值监听,分为观察者和被观察对象,当被观察对象中属性发生变化,被观察对象会通过观察者.
OC中,KVO常用方法:
KVO 使用步骤:
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
标签:
原文地址:http://www.cnblogs.com/naray/p/4546560.html