//監(jiān)聽(tīng)-(instancetype)init{? ? ? ? self = [super init];? ? ? ? if (self)? ? {? ? ? ? ? ? ? ? self.name = @"帥帥噠";? ? ? ? ? ? ? ? //注冊(cè)監(jiān)聽(tīng)//? ? ? ? NSKeyValueObservingOptionNew//? ? ? ? NSKeyValueObservingOptionOld? ? ? ? [self addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];? ? ? ? ? ? }? ? ? ? return self;? ? }//監(jiān)聽(tīng)回調(diào)方法-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context
{
NSLog(@"新值:%@!",change[@"new"]);
NSLog(@"舊值:%@!",change[@"old"]);
}
//移除監(jiān)聽(tīng)
-(void)dealloc
{
[self removeObserver:self forKeyPath:@"name"];
}
main.m
Person *person = [[Person alloc]init];
person.name = @"??";