您的位置:首页 > 移动开发 > Objective-C

Objective-c中的KVC、KVO

2012-12-31 22:24 253 查看
关于KVC(Key-Value-Coding)键-值编码的概念

1、键-值编码是一种用于间接访问对象属性的机制,使用该机制不需要调用setter、getter方法,和变量实例就可以访问对象的属性。

2、键-值编码方法在OC的非正式协议(类目)NSKeyCodingValue中被声明,默认的实现方法有NSObject提供。

3、键-值编码支持带有对象值的属性,同时也支持纯数值的类型和结构。非对象参数和返回类型会被识别并自动封装/解封。

下面我们来用KVC(Key-Value-Coding)在没有getter,setter方法的情况下访问变量的属性

如下,没有setter、getter方法以及@property

.h文件

#import <Foundation/Foundation.h>

@interface Dog : NSObject{
NSString *name;
}

@end


.m文件

#import "Dog.h"

@implementation Dog

@end
main文件

#import <Foundation/Foundation.h>
#import "Dog.h"

int main(int argc, const char * argv[])
{

@autoreleasepool {

Dog *dog = [[Dog alloc]init];

[dog setValue:@"娘希匹" forKey:@"name"];//设置键值对

NSString *name = [dog valueForKey:@"name"];//根据键取值

NSLog(@"The dog's name is ....%@...",name);
}
return 0;
}
打印结果:



2、看到上面的内容我们估计有个疑问,我们怎么访问属性中的属性呢,我们可以通过路径的方式来访问,同时我们也来看看纯数值的情况

Dog类的.h文件

#import <Foundation/Foundation.h>
@class Tooth;

@interface Dog : NSObject{
NSString *name;
int age;
Tooth *tooth;
}

@end
Dog类的.m文件

#import "Dog.h"

@implementation Dog

@end
Tooth类的.h文件

#import <Foundation/Foundation.h>

@interface Tooth : NSObject{

int num;
NSString *color;
}

@end
Tooth.m

#import "Tooth.h"

@implementation Tooth

@end


main文件

#import <Foundation/Foundation.h>
#import "Dog.h"
#import "Tooth.h"

int main(int argc, const char * argv[])
{

@autoreleasepool {

Dog *dog = [[Dog alloc]init];

[dog setValue:@"娘希匹" forKeyPath:@"name"];
[dog setValue:@5 forKeyPath:@"age"];

NSString *name = [dog valueForKey:@"name"];
NSNumber *age = [dog valueForKey:@"age"];

NSLog(@"The dog's name is ....%@...",name);
NSLog(@"%@",age);

Tooth *tooth = [[Tooth alloc]init];

[tooth setValue:@10 forKey:@"num"];
[tooth setValue:@"black" forKey:@"color"];
[dog setValue:tooth forKey:@"tooth"];

NSNumber *toothNum = [dog valueForKeyPath:@"tooth.num"];
NSString *toothColor = [dog valueForKeyPath:@"tooth.color"];

NSLog(@"The dog's teeth num is %@,color is %@",toothNum,toothColor);

//下面我们使用路径的方式
[dog setValue:@12 forKeyPath:@"tooth.num"];
[dog setValue:@"white" forKeyPath:@"tooth.color"];

NSNumber *toothNum1 = [dog valueForKeyPath:@"tooth.num"];
NSString *toothColor1 = [dog valueForKeyPath:@"tooth.color"];

NSLog(@"The dog's teeth num is %@,color is %@",toothNum1,toothColor1);

[tooth release];
[dog release];
}
return 0;
}

打印结果:



二、KVO(Key Value Observing)键值观察

键值观察是一种使对象获取其他对象的特定属性变化的通知机制。

KVO主要用于视图交互方面,比如界面的某些数据变化了,界面的显示也跟着需要变化,那就要建立数据和界面的关联
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  kvc kvo objective-C