IOS. OC.03 KVO-key-value observer, ios. oc.03kvo-
KVO Key, Value, Observing, that is, Key-Value observer. It provides such a mechanism that when the attributes of a specified object change, KVO automatically notifies the corresponding observer.
Unlike NSNotification, the key-value observation does not have any so-called central object to provide change notifications for all observers. Instead, when a change occurs, the notification is sent directly to the object in the observed state.
Three steps: register the observer, receive the change notification, and remove the observer. Example:
Create a project and two classes, one Baby and one Mother. Baby has a property hungryNum, called hunger value. When the hunger value changes, mother receives the hunger value change.
Baby. h
# Import <Foundation/Foundation. h>
@ Interface Baby: NSObject
@ Property (nonatomic, assign) NSInteger hungryNum;
@ End
Mother. m
# Import "Mother. h"
@ Implementation Mother
-(Void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context {
If ([keyPath isw.tostring: @ "hungryNum"]) {
// Print the current value and the previous value of hungryNum whenever the monitored property hungryNum changes.
NSLog (@ "% @", [change objectForKey: @ "new"], [change objectForKey: @ "old"]);
}
}
@ End
ViewController. m
# Import "ViewController. h"
# Import "Baby. h" // introduce the header file
# Import "Mother. h"
@ Interface ViewController ()
@ End
@ Implementation ViewController
-(Void) viewDidLoad {
[Super viewDidLoad];
Baby * xiaoxiao = [[Baby alloc] init]; // create an object
Mother * xiaoMama = [[Mother alloc] init];
// Register the observer. xiaoxiao adds the observer xiaoxiaoMama to observe the attributes of hungryNum.
[Xiaoxiao addObserver: xiaoMama forKeyPath: @ "hungryNum" options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context: nil];
Xiaoxiao. hungryNum = 10; // attach an initial value to the hungryNum attribute of xiaoxiao. Use a for loop to change the value of this attribute. The Listener is notified every time the value is changed.
For (xiaoxiao. hungryNum; xiaoxiao. hungryNum> 0; xiaoxiao. hungryNum --){
}
// Remove the observer. Note: if you do not remove the observer, the program will crash.
[Xiaoxiao removeObserver: xiaoMama forKeyPath: @ "hungryNum"];
}
Print result:
17:11:29. 735 OMG [2366: 148640] 10 0
17:11:29. 736 OMG [2366: 148640] 9 10
17:11:29. 736 OMG [2366: 148640] 8 9
17:11:29. 736 OMG [2366: 148640] 7 8
17:11:29. 736 OMG [2366: 148640] 6 7
17:11:29. 736 OMG [2366: 148640] 5 6
17:11:29. 736 OMG [2366: 148640] 4 5
17:11:29. 737 OMG [2366: 148640] 3 4
17:11:29. 737 OMG [2366: 148640] 2 3
17:11:29. 737 OMG [2366: 148640] 1 2
17:11:29. 737 OMG [2366: 148640] 0 1
In case of any errors, please do not give me any further information.