#import "HMViewController.h" #import "HMPerson.h" @interface HMViewController () @property (nonatomic, strong) HMPerson *p; @end @implementation HMViewController - (void)viewDidLoad { [super viewDidLoad]; // 运行时机制:runtime HMPerson *p = [[HMPerson alloc] init]; p.age = 20; [p addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil]; p.age = 30; self.p = p; } - (void)dealloc { [self.p removeObserver:self forKeyPath:@"age"]; } /** * 当监控的某个属性的值改变了就会调用 * * @param keyPath 属性名(哪个属性改了?) * @param object 哪个对象的属性被改了? * @param change 属性的修改情况(属性原来的值、属性最新的值) * @param context void * == id */ - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { NSLog(@"%@对象的%@属性改变了:%@", object, keyPath, change); } @end