KVC:Key-Value Coding
KVO:Key-Value Observing
Person.m
@interface Person : NSObject{ //该访问修饰符用于说明即使私有成员变量也可以通过kvc方式访问和赋值 @private NSString *_name; } @end @implementation Person @end
PersonObserve.m
@interface PersonObserve : NSObject @end @implementation PersonObserve - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ Person *p = (Person *)object; //使用kvc方式获取成员变量keypath的值 NSLog(@"%@",[p valueForKey:keyPath]); } @end
main.m
int main(int argc, const char * argv[]) { //观察者类 PersonObserve *po = [[PersonObserve alloc] init]; Person *p = [[Person alloc] init]; //使用kvo方式对成员变量“name”的属性值变化增加观察者po //po将在该属性值发生变化时执行- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context方法 [p addObserver:po forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil]; //通过kvc方式设置成员变量“name”的属性值 //出发观察者执行对应方法 [p setValue:@"yangys" forKey:@"name"]; //移除对私有成员变量“name”的观察 [p removeObserver:po forKeyPath:@"name"]; return 0; }
结果:
2015-03-02 20:57:52.487 KVC&KOC[843:24874] yangys Program ended with exit code: 0