Objective-C的KVC和KVO

KVC- Key-Value Coding.

KVO Key-Value Observing.

 

KVC是Objective-C提供的一种对象属性的访问机制。对于有面向对象编程习惯的程序员,这是别开生面的方式:不需要在源码通过特殊标志符“." 或 "->"来访问属性;KVC只需要在运行时提供属性名/路径名,就能获得某属性的值。

 

范例:

@interface Student : NSObject

{

NSString *name;

}

@end

 

@implementation Student

 

@end

 

///////通过Key访问属性name

 

Student * stu=[ [Student alloc] init];

 

[stu setValue:@"Ken Wu" forKey:@"name"];

NSString *newname = [stu valueForKey:@"name"]; //newname的值就是“Ken Wu"。

 

如果是复杂的对象,如以下Student有课程信息,记录其分数。

@interface Course : NSObject

{

NSString *name;

float score;

}

@end

 

@implementation Course

@end

@interface Student : NSObject

{

NSString *name;

Course *course;

}

@end

 

@implementation Student

@end

 

//////通过KeyPath访问课程分数

Student * stu=[ [Student alloc] init];

 

[stu setValue:@"Ken Wu" forKey:@"name"];

NSString *newname = [stu valueForKey:@"name"]; //newname的值就是“Ken Wu"。

 

[stu setValue:@"Ken Wu" forKey:@"name"];

Course *course =[ [Course alloc] init];

[stu setValue:course forKey:@"course"];

[stu setValue:@"科目1" forKeyPath:@"course.name"];

[stu setValue: 99.9 forKeyPath:@"course.score"];

 

float score = [stu valueForKeyPath:@"corse.score"]; //score的值就是 99.9

 

以上就是KVC的内容

KVO则在此基础上,对对象属性的变化增加了观察机制。一旦值发生了改变,就会回调已知函数

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

范例:

[stu addObserver:self forKeyPath:@"corse.score" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];

 

-(void)

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

If([keyPath isEqualToString:@"corse.score"]){

float newScore = [change objectForKey:@"new"];

float oldScore = [change objectForKey:@"old"];

If(newScore > oldScore){

NSLog(@"You made a progress!");

}

Else {

NSLog(@"You need move luck!");

}

}

}

 

以上就是KVO的内容

posted @ 2016-03-24 10:36  Ken_Wu  阅读(160)  评论(0编辑  收藏  举报