Monitor key is that you can monitor changes in the value of a property of the object;
First of all, in the project, create a new class of Person
@interface Person : NSObject @property (nonatomic, copy) NSString *name; @end
ViewController introduced in the header file "Person", began testing the use of KVO
- (void)viewDidLoad { [super viewDidLoad]; Person *person = [[Person alloc] init]; person.name = @"珠珠"; [person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"testKVO"]; person.name = @"小雅"; [person removeObserver:self forKeyPath:@"name"]; } - (void) the observeValueForKeyPath: (NSString *) keyPath ofObject: (ID) Object Change: (NSDictionary <NSKeyValueChangeKey, ID> *) Change context :( void * ) context { NSLog ( @ " keypaht% = @, @% = Object, Change = % @, context =% @ " , keyPath, Object , Change, context); // NSKeyValueChangeOldKey can use the" old "instead, but get it, if the system modifies old as the" Old ", then it would not obtain, so suggested NSKeyValueChangeOldKey (NSLog @ " Get value before being modified =% @ " , Change [NSKeyValueChangeOldKey]); // NSKeyValueChangeNewKey may be "new" instead, but acquired, and if the system modified new is "new", then will get less, it is recommended to use NSKeyValueChangeNewKey NSLog ( @ "= Modified value after acquisition% @", change[NSKeyValueChangeNewKey]); }
Run the program to give a value out of the following: