[Original] obj-c Programming 17: key value observation (KVO)

Source: Internet
Author: User

[Original] obj-c Programming 17: key value observation (KVO)

Original article: [original] obj-c Programming 17: key value observation (KVO)

Links to series columns: objective-c Programming Series

 

After finishing the previous article on KVC, I can't help but talk about its application KVO (Key-Value Observing. KVO is similar to the hook function in ruby. When an object property changes, the observer can track the changes and then observe or modify the changes, this is done through the callback function registered by the callback observer. To use key-value observation, three conditions must be met:

1. The observed object must use the KVC-compliant accessors for the observed attributes;

2. The observer must implement the notification receiving method (callback method):-observeValue: forKeyPath: ofObject: change: context:. This method is called when the value changes and can be customized: for example, receiving new and original values and other custom information at the same time;

3. The observer registers a specific path of a specific object through the-addObserver: forKeyPath: options: context: method.

It should also be noted that after the observer completes the observation of the observer, he must remove himself; otherwise, after the observer is released, the notification message from the change of the observer will be nowhere to be sent, the reference may crash. In addition, multiple observers can be used to observe the same path of the same object, similar to forming an observation chain.

Below I will write a simple example to illustrate the above content with code:

1 # import <Foundation/Foundation. h> 2 3 # define msg (...) NSLog (_ VA_ARGS _) 4 # define mki (x) [NSNumber numberWithInt: x] 5 6 @ interface Son: NSObject {7 NSString * girl_friend_name; 8} 9 @ property NSString * girl_friend_name; 10-(void) think; 11-(void) fall_in_love_with :( NSString *) girl_name; 12 @ end13 14 @ implementation Son15 @ synthesize girl_friend_name; 16 17-(void) fall_in_love_with :( NSString *) girl_n Ame {18 self. girl_friend_name = girl_name; 19} 20 21-(void) think {22 msg (@ "My love girl is % @... Does baba know? ", Girl_friend_name); 23} 24 @ end25 26 @ interface Baba: NSObject {27 Son * son; 28} 29 @ property Son * son; 30 @ end31 32 @ implementation Baba33 @ synthesize son; 34 35-(id) initWithSon :( Son *) son_v {36 self = [super init]; 37 if (self) {38 son = son_v; 39 [son addObserver: self forKeyPath: @ "girl_friend_name" \ 40 options :( NSKeyValueObservingOptionNew | \ 41 NSKeyValueObservingOptionOld | Login) \ 42 context: nil]; 43} 44 return self; 45} 46 47-(void) observeValueForKeyPath :( NSString *) key_path \ 48 ofObject :( id) obj change :( NSDictionary *) change \ 49 context :( void *) context {50 51 NSString * old_name = [change objectForKey: NSKeyValueChangeOldKey]; 52 NSString * new_name = [change objectForKey: NSKeyValueChangeNewKey]; 53 if (! Old_name) {55 // NSKeyValueObservingOptionInitial option, the first hook will send a message 56 // after each change will send a message. 57 msg (@ "Yes, It's first time to induction son's girl_name !!! "); 58} else {59 if ([new_name is1_tostring: @" libinbin "]) {60 [obj fall_in_love_with: @" fanbinbin "]; 61} 62 msg (@ "My son's % @ change from % @ to % @... that's OK? :( ", \ 63 key_path, old_name, new_name); 64} 65} 66 67-(void) dealloc {68 [son removeObserver: self forKeyPath: @" girl_friend_name "]; 69 son = nil; 70 // [super dealloc]; 71} 72 @ end73 74 int main (int argc, char * argv []) 75 {76 @ autoreleasepool {77 Son * son = [[Son alloc] init]; 78 [son fall_in_love_with: @ "lili"]; 79 [son think]; 80 81 Baba * baba = [[Baba alloc] initWithSon: son]; 82 [son fall_in_love_with: @ "mimi"]; 8 3 [son think]; 84 85 // The son liked libinbin,... 86 [son fall_in_love_with: @ "libinbin"]; 87 // his father used the special function to change it to fanbinbin! 88 [son think]; 89} 90 return 0; 91}

To put it simply, Dad naturally wants to monitor his son's girlfriend at any time, but this dad can even monitor him and forcibly change his son's girlfriend... just consider fun as an example. Description:

-AddObserver registers the observer of the object. Other optional values of options are as follows. You can select multiple values:

The context parameter is of unknown significance. If anyone knows, don't forget to tell me about it. For the meaning of the NSKeyValueObservingOptionInitial flag, see code comments.

-Change in the observeValueForKeyPath callback method is a dictionary parameter, including:

The NSKeyValueChangeKindKey specifies the type of change received, which may have the following values:

The code in the book adds a backtracking call to the method with the same name in the parent class at the end of the method definition:

[Super observeValueForkeyPath: key_path ofObject: obj change: change context: ctx];

But I did not write this in the code. In the book, the observer's dealloc method finally has a [super dealloc], but this will cause errors during compilation under ARC. Remove it temporarily. The code execution result is as follows:

 1 apple@kissAir: objc_src$./k 2  3 2014-07-06 20:11:26.757 k[2109:507] My love girl is lili ... Does baba know? 4  5 2014-07-06 20:11:26.759 k[2109:507] Yes , It's first time to induction son's girl_name!!! 6  7 2014-07-06 20:11:26.760 k[2109:507] My son's girl_friend_name change from lili to mimi ... That's OK? :( 8  9 2014-07-06 20:11:26.760 k[2109:507] My love girl is mimi ... Does baba know?10 11 2014-07-06 20:11:26.761 k[2109:507] My son's girl_friend_name change from libinbin to fanbinbin ... That's OK? :(12 13 2014-07-06 20:11:26.761 k[2109:507] My son's girl_friend_name change from mimi to libinbin ... That's OK? :(14 15 2014-07-06 20:11:26.761 k[2109:507] My love girl is fanbinbin ... Does baba know?

Dad has good supervision, but his son is not happy. How can the son of hack make his father so infringe on his privacy? What should we do? If the change notification is not automatically passed, it will not end! To implement manual notifications, You need to override Son's class method + automaticallyNotifiesObserversForKey to inform obj-c that you do not want to automatically notify the observer of your changes. Note that this is a class method! You can return NO for a specific key name:

1 +(BOOL)automaticallyNotifiesObserversForKey:(NSString *)key{2         if([key isEqualToString:@"girl_friend_name"])3             return NO;4         return YES;5     }

Add the above class methods to the Son class implementation and re-compile and run them:

1 apple@kissAir: objc_src$./k2 3 2014-07-06 20:37:36.726 k[2180:507] My love girl is lili ... Does baba know?4 5 2014-07-06 20:37:36.729 k[2180:507] Yes , It's first time to induction son's girl_name!!!6 7 2014-07-06 20:37:36.729 k[2180:507] My love girl is mimi ... Does baba know?8 9 2014-07-06 20:37:36.730 k[2180:507] My love girl is libinbin ... Does baba know?

Dad, "No! But if this is so long, dad will doubt it. Is it swollen? Is my baby son never in love? This cannot be done! So the smart hack son can manually notify his dad of the tampered content! Specifically: Call-willChangeValueForKey before the Son property writer method changes, then call-didChangeValueForKey after the change, and rewrite the writer method. The complete code after the modification is as follows:

1 # import <Foundation/Foundation. h> 2 3 # define msg (...) NSLog (_ VA_ARGS _) 4 # define mki (x) [NSNumber numberWithInt: x] 5 6 @ interface Son: NSObject {7 NSString * girl_friend_name; 8} 9 // if the default attribute is atomic, if the custom writer method must also customize the reader method, 10 // or change the attribute to nonatomic mode. 11 @ property (nonatomic) NSString * girl_friend_name; 12-(void) think; 13-(void) fall_in_love_with :( NSString *) girl_name; 14 @ end 15 16 @ implementation Son 17 @ synthesize girl_friend_name; 18 19-(void) fall_in_love_with :( NSString *) girl_name {20 self. girl_friend_name = girl_name; 21} 22 23-(void) think {24 msg (@ "My love girl is % @... does baba know? ", Girl_friend_name); 25} 26 27 + (BOOL) automaticallyNotifiesObserversForKey :( NSString *) key {28 if ([key isEqualToString: @" girl_friend_name "]) 29 return NO; 30 return YES; 31} 32 33-(void) setGirl_friend_name :( NSString *) name {34 [self willChangeValueForKey: @ "girl_friend_name"]; 35 // Let Dad think that he is in love with female. 36 girl_friend_name = @ "female"; 37 [self didChangeValueForKey: @ "girl_friend_name"]; 38 // restore his true color, BAD BOY... :) 39 girl_friend_name = name; 40} 41 @ end 42 43 @ interface Baba: NSObject {44 Son * son; 45} 46 @ property Son * son; 47 @ end 48 49 @ implementation Baba 50 @ synthesize son; 51 52-(id) initWithSon :( Son *) son_v {53 self = [super init]; 54 if (self) {55 son = son_v; 56 [son addObserver: self forKeyPath: @ "girl_friend_name" \ 57 options :( NSKeyValueObservingOptionNew | \ 58 NSKeyValueObservingOptionOld | N SKeyValueObservingOptionInitial) \ 59 context: nil]; 60} 61 return self; 62} 63 64-(void) observeValueForKeyPath :( NSString *) key_path \ 65 ofObject :( id) obj change :( NSDictionary *) change \ 66 context :( void *) context {67 68 NSString * old_name = [change objectForKey: NSKeyValueChangeOldKey]; 69 NSString * new_name = [change objectForKey: NSKeyValueChangeNewKey]; 70 71 if (! Old_name) {72 // NSKeyValueObservingOptionInitial option, the first hook will send a message 73 // after each change will send a message. 74 msg (@ "Yes, It's first time to induction son's girl_name !!! "); 75} else {76 if ([new_name is1_tostring: @" libinbin "]) {77 [obj fall_in_love_with: @" fanbinbin "]; 78} 79 msg (@ "My son's % @ change from % @ to % @... that's OK? :( ", \ 80 key_path, old_name, new_name); 81} 82} 83 84-(void) dealloc {85 [son removeObserver: self forKeyPath: @" girl_friend_name "]; 86 son = nil; 87 // [super dealloc]; 88} 89 @ end 90 91 int main (int argc, char * argv []) 92 {93 @ autoreleasepool {94 Son * son = [[Son alloc] init]; 95 [son fall_in_love_with: @ "lili"]; 96 [son think]; 97 98 Baba * baba = [[Baba alloc] initWithSon: son]; 99 [son fall_in_lov E_with: @ "mimi"]; 100 [son think]; 101 102 // The son liked libinbin,... 103 [son fall_in_love_with: @ "libinbin"]; 104 // his father used the special function to change it to fanbinbin! 105 [son think]; 106} 107 return 0; 108}

The compilation and running results are as follows:

Apple @ kissAir: objc_src $./k2014-07-06 20:58:59. 284 k [2270: 507] My love girl is lili... Does baba know? 20:58:59. 286 k [2270: 507] Yes, It's first time to induction son's girl_name !!! 20:58:59. 287 k [2270: 507] My son's girl_friend_name change from lili to female students... That's OK? :( 20:58:59. 287 k [2270: 507] My love girl is mimi... Does baba know? 20:58:59. 288 k [2270: 507] My son's girl_friend_name change from mimi to female students... That's OK? :( 20:58:59. 288 k [2270: 507] My love girl is libinbin... Does baba know?

This time, the father was dumb and thought that his son had been in a bid with the female schoolmaster. This is also true for all the kids shoes.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.