KVO (key value observe) key-value observation is a core concept in iOS, which is simply understood to be used when an object a (or multiple objects) is changing one or more of the properties of B to listen for an object.
- Advantages of KVO
When an object has a property change, KVO automatically notifies the other party that the architecture has several benefits. First, developers do not need to implement such a scenario: each time the property changes to send a message notification, which is the biggest advantage of the KVO mechanism, because the scheme has been clearly defined, to obtain framework-level support, can be easily adopted, developers do not need to add any code, do not need to design their own developer model, Can be used directly in the project, followed by the KVO architecture is very powerful, it is easy to support multiple observers to observe the same property, and related values
2, shortcomings, real-time monitoring of object property value changes, very consumption of system performance.
KVO's face question.
1. What are the differences and usages of nsnotification and KVO? When should I use notifications, when should I use KVO, and what are the differences in their implementation? is it possible to implement a similar function with protocol and delegate (or an Array of delegate)? If possible, what are the potential problems? If not, why?
A:KVO can only monitor the change of properties, implemented by the property name of the NSString type. However, automatic monitoring is implemented, and when the property value changes, the Observer is automatically notified and no more code is added.
Nsnotification more flexible, can monitor more content, but need to be the observer manually send notifications, the observer can respond.
protocol by adding a Nsarray can also achieve similar functions, but the implementation of the need to handle the delegate of the addition and deletion of their own property changes in the manual notification, more cumbersome, error- prone
Introduction to notification mechanisms
/**
* Nsnotificationcenter messages between two objects, or passing messages between multiple objects
* A object triggers an event (a object cannot be completed), requires a B object to complete, a object (void) Postnotificationname: (NSString *) AName object: (ID) anobject ;
* Postnotificationname Send the name of the message
* which object is sent by object
*-(void) Addobserver: (ID) Observer selector: (SEL) aselector name: (NSString *) AName object: (ID) anobject; who receives the notification and receives the notification after the implementation method (SEL) Aselector
* Removeobserver Removal Notice
*/
The demo code for the following kvo:
1 Person.h Content2 3 #import<Foundation/Foundation.h>4 5 @interfacePerson:nsobject6 7@property (nonatomic, copy) NSString *name;8@property (nonatomic, assign)intAge ;9 Ten //-(void) dognamechange; One A //-(void) dogagechange; - - @end the - - person.m File Contents - #import "Person.h" + - @implementation Person + A //Listener Implementation Method at- (void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID)ObjectChange: (nsdictionary *) Change context: (void*) Context - { - if([KeyPath isequal:@"name"])//the dog's Name property has changed - { -NSLog (@"dog-name-change,old:%@, New:%@;context =%@", [Change Objectforkey:nskeyvaluechangeoldkey],[change objectforkey:nskeyvaluechangenewkey],context); - in } - to if([KeyPath isequal:@" Age"])//The Age property of dog has changed + { -NSLog (@"dog-age-change,old:%@, New:%@;context =%@", [Change Objectforkey:nskeyvaluechangeoldkey],[change objectforkey:nskeyvaluechangenewkey],context); the } * } $ Panax Notoginseng //-(NSString *) Description - //{ the //return [NSString stringwithformat:@ "name-%@, age-%d", self.name,self.age]; + //} A // the // + //-(void) Dognamechange - //{ $ //NSLog (@ "Dognamechange"); $ ////[Self removeobserver:self forkeypath:@ "name"]; - //} - // the //-(void) Dogagechange - //{Wuyi //NSLog (@ "Dogagechange"); the //} - Wu @end - About Dog.h Content $ - #import<Foundation/Foundation.h> - - @classPerson ; A @interfaceDog:nsobject + the -@property (nonatomic, weak) person *Onwer; $ @property (nonatomic, assign) Nsinteger age; the@property (nonatomic, copy) NSString *name; the the @end the - DOG.M Content in the #import "Dog.h" the About @implementationDog the the the @end + - VIEWCONTROLLER.M Content the Bayi #import "SDViewController.h" the #import "Person.h" the #import "Dog.h" - - @implementationSdviewcontroller the the- (void) Viewdidload the { the [Super Viewdidload]; -Person *p =[[Person alloc] init]; theP.name =@"Zhang San"; theP.age = -; the 94Dog *d =[[Dog alloc] init]; theD.age =Ten; theD.name =@"Old Dog"; the 98 //KVO Walkthrough--Listening to changes in an object's properties About[D addobserver:p Forkeypath:@" Age"Options: (0x01|0x02) Context:@"Helloage"]; -[D addobserver:p Forkeypath:@"name"Options: (0x01|0x02) Context:@"Helloname"];101 102 //KVC Assignment Value103[D setvalue:@ ( -) Forkeypath:@" Age"];104[P SetValue:@"John Doe"Forkeypath:@"name"]; the[P setvalue:@ (Ten) Forkeypath:@" Age"];106[D SetValue:@"Puppy Dog"Forkeypath:@"name"];107 108 //[D removeobserver:p forkeypath:@ "name"];//Remove Kvo109 //[D removeobserver:p forkeypath:@ "age"];//Remove Kvo the 111 the}
Introduction to important methods in header files in Kvo
/* Because the receiver has been registered as an observer in relation to the object's critical path value, the value is notified to change. The Change dictionary always contains the Nskeyvaluechangekindkey item whose value is a NSNumber wrapper nskeyvaluechange (using-[NSNumber unsignedintegervalue]). The meaning of Nskeyvaluechange depends on what attributes and key line identification: -for any type of attribute (attribute, to one-to-one relationship, Or an ordered or unordered one-to-many relationship) nskeyvaluechangesetting indicates that the Observer has received the-setvalue:forkey: message, or that the key-value encoding-compatible setting method key has been called, Or a-willchangevalueforkey:/-didchangevalueforkey: To be called in other ways. -For _ordered_ a one-to-many relationship, Nskeyvaluechangeinsertion, Nskeyvaluechangeremoval and Nskeyvaluechangereplacement indicate that the mutated message has been sent to the array returned by-mutablearrayvalueforkey: The message sent to the object, Or send to an ordered collection returned by-mutableorderedsetvalueforkey: The message is sent to the object, or the key of an encoded standard array or ordered set mutation method in the key value has been called, Or a-willchange:valuesatindexes:forkey:/-didChange:valuesAtIndexes:forKey: To have otherwise been called. -For _unordered_ a one-to-many relationship, Nskeyvaluechangeinsertion, Nskeyvaluechangeremoval and Nskeyvaluechangereplacement (on Mac OS10.4) indicates that the mutated message has been sent to the collection returned by-mutablesetvalueforkey: A message sent to the object, or a key-value encoding compatible set of gene mutation methods to which the key has been called, or a- WillChangeValueForKey:withSetMutation:usingObjects:/-didchangevalueforkey:withsetmutation:usingobjects: Yes, otherwise it is called. For any form of property, the change dictionary has a Nskeyvaluechangenewkey item, if nskeyvalueobservingoptionnew is specified at the time of the observer registration, this is the correct change, which is not prior notice. The change dictionary contains nskeyvaluechangeoldkey if you specify Nskeyvalueobservingoptionold, this is the correct one. See the Nskeyvalueobservernotification informal protocol method for what the values of these entries can be comments. For a _ordered_ one-to-many relationship, the change dictionary always contains the index of an Nskeyvaluechangeindexeskey entry that contains the inserted, deleted, or replaced object. Unless the change is nskeyvaluechangesetting a nsindexset. If the Nskeyvalueobservingoptionprior (in the Mac OS10.5 introduced) specifies the time at which the Observer is registered, and the notification is a change that was previously sent to, as a result, the change dictionary contains the Nskeyvaluechangenotificationispriorkey item whose value is a nsnumber wrapping paper (with-[ NSNumber of Boolvalue]). The background is always at the time of the observer registration, in the same pointer. *///Listener Implementation Method-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (Nsdictionary *) change Context: (void *) context;
Registered Observer--observer who is listening, keypath--listening to which property value options--new values and old values context--messages sent to observer
-(void) Addobserver: (NSOBJECT *) Observer Forkeypath: (NSString *) keypath options: (nskeyvalueobservingoptions) options Context: (void *) context;
Remove Observer-(void) Removeobserver: (NSOBJECT *) Observer Forkeypath: (NSString *) KeyPath context: (void *) Context Ns_ AVAILABLE (10_7, 5_0);-(void) Removeobserver: (NSOBJECT *) Observer Forkeypath: (NSString *) KeyPath;
KVO in iOS