KVO, that is, key-value observing, provides a mechanism. When the attribute of a specified object is modified, the object will receive a notification. In short, KVO automatically notifies the corresponding observer after the attribute of the specified object to be observed is modified.
// KVO is based on KVC. The observer can observe a certain attribute (key) of an object, but an event is triggered when the value of this attribute changes.
// The following concepts are involved in KVO:
// The observer is usually a model.
// The observer is usually a controller.
// An attribute of the key being observed
// Value corresponding to the value Key
// There is a design pattern in the design pattern: Observer Pattern
// KVO is an implementation method of the observer mode and belongs to the observer design mode.
// ***** KVO usage process
// 1. Create the observed object
// 2. Specify the Observer for the Observer
// 3. Implement the callback Method
// 4. Modify the observed attribute (the callback method will be triggered)
// 5. Remove the observer
Instance:
Create a person class. The person class has a name attribute.
Code in the root controller viewcontroller. m
# Import "viewcontroller. H "# import" person. H "@ interface viewcontroller () {person * _ p;} @ end @ implementation viewcontroller-(void) dealloc {[_ p removeobserver: Self forkeypath: @" name "]; [_ P release]; [Super dealloc];}-(void) viewdidload {[Super viewdidload]; // P is used as the observer _ p = [[person alloc] init]; [_ p addobserver: Self forkeypath: @ "name" Options: nskeyvalueobservingoptionnew | nskeyvalueobservingoptionold context: @ "hello"]; _ p. name = @ "Lisi"; // do any additional setup after loading the view, typically from a nib .} // This method is triggered only when the attributes of the observer change-(void) observevalueforkeypath :( nsstring *) keypath ofobject :( ID) object change :( nsdictionary *) change context :( void *) Context {nslog (@ "Object = % @", object); nslog (@ "keypath = % @", keypath ); nslog (@ "change = % @", change); nslog (@ "context = % @", context);}-(void) didreceivemorywarning {[Super didreceivemorywarning]; // dispose of any resources that can be recreated .} @ end