Objective-c key-value observer KVO mode Learning

Source: Internet
Author: User

The KVO key-value observer mode is an important mechanism of cocoa similar to the notification mode. When the attributes of the observer change, the observer performs corresponding operations.

Create a new person class to inherit nsobject, add the name and age attributes, and then create a personobserver class to inherit nsobject at the same time

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

Method

The details are as follows:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{    if ([keyPath isEqualToString:kPathName]) {        NSLog(@"old name:%@ \nnew name:%@", [change objectForKey:@"old"], [change objectForKey:@"new"]);                //Do something what you want to do        //...        return;    }    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];}

Use keypath to determine whether the property of our listener has changed. If yes, perform the corresponding operation.

Add an observer to an object:

Person *person = [[Person alloc] init];    [person setName:@"old name"];    PersonObserver *observer = [[PersonObserver alloc] init];        [person addObserver:observer forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];        [person setName:@"new name"];        [person removeObserver:observer forKeyPath:@"name"];

Running effect:

2013-03-05 16:08:04.347 learnOcKVO[10980:11303] old name:old name new name:new name
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.