1, KVO's introduction
KVO Full name Key-value observing. The Chinese is called the key value observation. KVO is actually an observer pattern, the observer will be notified when the key value changes, it is easy to implement the separation of the view component and the data model, when the data model's property value changes as the listener's view component will be fired, when fired will callback the listener itself. Simpler and more straightforward than NOTIFICATION,KVO.
The Kvo method is provided by Nskeyvaluecoding, which is the NSObject category, which means that almost all objects in OBJC support KVO operations.
KVO the Setter/getter method to implement instance variables
2, the realization of KVO
0) The use of KVO is also very simple, is simple 3 steps.
(1) Register the properties of the object to be observed AddObserver:forKeyPath:options:context:
(2) Implement ObserveValueForKeyPath:ofObject:change:context: Method, this method is called automatically when the observed property changes. In this method also through nskeyvalueobservingopt Ionnew This parameter requires that the new value be passed in the dictionary.
(3) Cancellation of registration observation RemoveObserver:forKeyPath:context:
1) Registration
Implementation method:
-(void) Addobserver: (NSOBJECT *) Observer Forkeypath: (NSString *) keypath options: (nskeyvalueobservingoptions) options Context: (Nullable void *) context;
Method Parameters:
Object: Objects being observed
Observer: Object of observation
Forkeypath with the name of the property, such as UIView frame, center, etc.
Options: There are 4 values, namely:
Nskeyvalueobservingoptionnew provide the value before the change to the processing method
Nskeyvalueobservingoptionold provide the value after the change to the processing method
Nskeyvalueobservingoptioninitial provides the initialization value to the processing method, and once registered, it is called immediately. Usually it will have a new value without the old value.
Nskeyvalueobservingoptionprior is called 2 times. Before the value changes and after the value changes.
Note: In the example of 0, it means to go in without any parameters.
Context: can be brought into some parameters, in fact, this is very useful, any type can, their strong turn on the good.
2) Monitoring
Implementation method:
-(void) Observevalueforkeypath: (Nullable NSString *) KeyPath Ofobject: (Nullable ID) object change: (Nullable nsdictionary<nsstring*, id> *) Change context: (Nullable void *) context;
This method is called automatically when the observed property changes. In this method, it is also necessary to pass the new value in dictionary through the nskeyvalueobservingoptionnew parameter.
Method Parameters:
KeyPath: Corresponding Forkeypath
Object: Objects to be observed
Change: Corresponding to the nskeyvalueobservingoptionnew, Nskeyvalueobservingoptionold, etc. in the options
Context: Corresponding context
3) Cancellation of registration observation
Implementation method:
-(void) Removeobserver: (NSOBJECT *) Observer Forkeypath: (NSString *) KeyPath context: (Nullable void *) Context Ns_ AVAILABLE (10_7, 5_0);
Method Parameters:
Ditto
3. Specific implementation code
Main.m
1 //2 //main.m3 //KVO Concrete Implementation4 //5 //Created by Ma C on 16/5/18.6 //copyright©2016 year Pengsheng rime. All rights reserved.7 //8 9 #import<Foundation/Foundation.h>Ten #import "Person.h" One #import "Watch.h" A - intMainintargcConst Char*argv[]) { - @autoreleasepool { the -Person *person =[[Person alloc] init]; - -Watch *watch =[[Watch alloc] init]; + -Person.watch =Watch; + A [Person Registerobserver]; at -Person.name =@"PSS"; - -Person.name =@"PBB"; - - } in return 0; -}main.m
Person.h
1 //2 //Person.h3 //KVO Concrete Implementation4 //5 //Created by Ma C on 16/5/18.6 //copyright©2016 year Pengsheng rime. All rights reserved.7 //8 9 #import<Foundation/Foundation.h>Ten #import "Watch.h" One A @interfacePerson:nsobject - -@property (nonatomic, copy) NSString *name; the -@property (nonatomic, strong) Watch *Watch; - -- (void) Registerobserver; + - @end
Person.h
Person.m
1 //2 //person.m3 //KVO Concrete Implementation4 //5 //Created by Ma C on 16/5/18.6 //copyright©2016 year Pengsheng rime. All rights reserved.7 //8 9 #import "Person.h"Ten One @implementation Person A -- (void) Dealloc { - the[Self RemoveObserver:self.watch Forkeypath:@"name"]; - } - -- (void) Registerobserver { + -[Self AddObserver:self.watch Forkeypath:@"name"options:nskeyvalueobservingoptionnew|Nskeyvalueobservingoptionold Context:nil]; + } A @endperson.m
Watch.m
1 //2 //WATCH.M3 //KVO Concrete Implementation4 //5 //Created by Ma C on 16/5/18.6 //copyright©2016 year Pengsheng rime. All rights reserved.7 //8 9 #import "Watch.h"Ten One @implementationWatch A- (void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID)ObjectChange: (Nsdictionary<nsstring *,ID> *) Change context: (void*) Context { - -NSLog (@"new =%@", [Change Valueforkey:@"New"]); the -NSLog (@"Old =%@", [Change Valueforkey:@" Old"]); - -NSLog (@"---------------------------"); + } - @endWatch.h
Log Print Logs
4, KVO Common crash errors and solutions
1) do not implement Dealloc, register, delete, monitor operation method in exact position
2) The remove operation in Dealloc is not implemented
5, manual implementation of KVO
1+ (BOOL) Automaticallynotifiesobserversforkey: (NSString *) Key {2 3BOOL automatic =YES;4 if([Key isequaltostring:@" Age"]) {5automatic =NO;6}Else {7automatic =[Super Automaticallynotifiesobserversforkey:key];8 }9 Ten returnAutomatic; One } A -- (void) Setage: (int) Age { - the //Set KVO manually - - if(_age! =Age ) { - +[Self Willchangevalueforkey:@" Age"]; - +_age =Age ; A at[Self Didchangevalueforkey:@" Age"]; - - } -}
6, the realization principle of KVO
When an instance of a class uses KVO for the first time, a derived class of the class is created dynamically during runtime, and the naming convention for the class is typically prefixed with nskvonotifying, with the original class name suffix. And the ISA pointer to the prototype object points to the derived class. The setter method that uses the Kvo property is also overloaded in the derived class to implement a true notification mechanism in the overloaded setter method, just as we did in the previous manual implementation of KVO. This is done by invoking the setter method based on the setting property, and by overriding the notification mechanism required by the KVO. Of course, if you want to change the property value by following the KVO property setting, you cannot implement KVO if you modify only the member variable that corresponds to the property.
The KVO of the Observer pattern in iOS