Use of objective-C syntax in KVO

Source: Internet
Author: User

Introduction:

In the previous article, we talked about KVC. In this article, we learned KVO. The full name is: key value observing. the literal translation is: key value-based observer.

So what is its use? KVO is mainly used for view interaction. For example, if some data on the interface changes and the display of the interface also changes, it is necessary to establish a correlation between data and the interface.

KVO provided in objc solves this problem. The following example shows how to use KVO by observing the change of course name on the displayed page.

The student class is named student and the page class is pageview.

From the official website of Apple: bankobject in the figure is like pageview, while personobject is like student,

Pageview observe the changes of student.

1. Add student class.

. H

#import <Foundation/Foundation.h>@interface Student : NSObject{    NSString *name;    NSString *courseName;}-(void)changeCourseName:(NSString*) newCourseName;@end

The class includes name and Course name coursename. Add a changecoursename method that can change the course name. For comparison later, check whether there will be a callback when the course name is changed directly.

Implementation file. m

#import "Student.h"@implementation Student-(void)changeCourseName:(NSString*) newCourseName{    courseName = newCourseName;}@end

The implementation class implements the method.

2. Page class implementation

. H file

#import <Foundation/Foundation.h>@class Student;@interface PageView : NSObject{    Student *student;}-(id)init:(Student*)initStudent;@end

. M file

#import "PageView.h"#import "Student.h"@implementation PageView-(id)init:(Student*)initStudent{    if (self = [super init]) {        student = initStudent;        [student addObserver:self                   forKeyPath:@"courseName"                      options:NSKeyValueObservingOptionOld                            |NSKeyValueObservingOptionNew context:nil];    }    return self;}- (void) dealloc{     [student removeObserver:self forKeyPath:@"courseName" context:nil];    [super dealloc]; }-(void)observeValueForKeyPath:(NSString *)keyPath                      ofObject:(id)object                        change:(NSDictionary *)change                       context:(void *)context{    if ([keyPath isEqual:@"courseName"]) {        NSLog(@"PageView课程被改变了");        NSLog(@"PageView新课程是:%@ 老课程是:%@", [change objectForKey:@"new"],[change objectForKey:@"old"]);    }}@end

When init is initialized, add the observer to the student instance and remove the observer when it is released.

3. Observation

In the main function

#import "Student.h"#import "Course.h"#import "PageView.h"int main(int argc, const char * argv[]){    @autoreleasepool {        Student *student = [[[Student alloc]init]autorelease];        [student changeCourseName:@"数学课"];        NSLog(@"初始值:%@", [student valueForKey:@"courseName"]);                //创建页面实例        PageView *pageview = [[[PageView alloc]init:student]autorelease];                [student setValue:@"化学课" forKey:@"courseName"];          }    return 0;}

Create a student instance, set the course to a mathematics class, and initialize it with student when creating the page class. This is a page class that has been observed by students.

 

Set a new value for the course to chemistry. Run the following command to print the result:

 

16:29:21. 561 objectivec [2192: 403]Initial Value:Mathematics

16:29:21. 565 objectivec [2192: 403] pageviewCourse changed

16:29:21. 566 objectivec [2192: 403] pageviewNew course is:Chemistry Course Old Course is:Mathematics

You can see that the callback in the pageview class is called, and pageview receives the student course data update information.

4. directly change the course information comparison
#import "Student.h"#import "Course.h"#import "PageView.h"int main(int argc, const char * argv[]){    @autoreleasepool {        Student *student = [[[Student alloc]init]autorelease];        [student changeCourseName:@"数学课"];        NSLog(@"初始值:%@", [student valueForKey:@"courseName"]);                //创建页面实例        PageView *pageview = [[[PageView alloc]init:student]autorelease];                [student setValue:@"化学课" forKey:@"courseName"];        [student changeCourseName:@"英语课"];        NSLog(@"直接改变的课程为:%@", [student valueForKey:@"courseName"]);    }    return 0;}

Directly call the changecoursename method to change the course and print the result:

16:32:06. 230 objectivec [2240: 403]Initial Value:Mathematics

16:32:06. 237 objectivec [2240: 403] pageviewCourse changed

16:32:06. 238 objectivec [2240: 403] pageviewNew course is:Chemistry Course Old Course is:Mathematics

16:32:06. 239 objectivec [2240: 403]Directly changed the course:English class

We can see that the callback of pageview is not called.It indicates that the method registered by the observer will be called back only when the value is changed through key-value encoding (KVC.

Here is the KVO documentation on the official website of Apple. If you are good at English, you can see:

Https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html#//apple_ref/doc/uid/10000177-BCICJDHA

Use of objective-C syntax in KVO

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.