kvc,(key-value-coding).
1访问变量(私有变量)。
正常的public变量忽略,如果是private私有变量,通过get方法是访问不到的。但是通过kvc可以访问私有变量.
比如在privateProperty类中定义一个私有属性 name:
@interface privateProperty : NSObject
{
@public
NSString *clName;
@private
NSString *name;
}
@end
然后通过kvc赋值调用:
privateProperty *pro = [[privateProperty alloc]init];
[pro setValue:@"Arno" forKey:@"name"];
NSLog(@"%@",[pro valueForKey:@"name"]);
[pro printName]; //本类中打印,验证是否是原来的name
printName方法:
-(void)printName{
NSLog(@"私有属性name: %@",name);
}
打印出的内容:
15:04:53.998 KVC[3828:252039] Arno
5:04:53.999 KVC[3828:252039] 私有属性:Arno
说明privateProperty的name被赋值。
2.可以直接访问Array中的属性值:直接上代码:
#import <Foundation/Foundation.h>
NSString *userId;
@property(nonatomic,strong)NSString *userName;
在main方法里面测试:
NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
for (int i = 0; i<3; i++) {
model *mod = [[model alloc]init];
[mod setValue:[NSString stringWithFormat:@"%d",i] forKeyPath:@"userId"];
[mod setValue:@"zs" forKeyPath:@"userName"];
[array addObject:mod];
}
NSArray *userId = [array valueForKeyPath:@"userId"];
NSLog(@"userId: %@",userId);
打印结果:
userId: (
0,
1,
2
)
3.数据-》模型:
NSDictionary *dic = @{@"userId":@"1",@"userName":@"zs"};
model *mod = [[model alloc]init];
[mod setValuesForKeysWithDictionary:dic];
NSLog(@"name: %@, id: %@",mod.userName,[mod valueForKey:@"userId"]);
打印结果:
name: zs, id: 1
属性名和key必须书写一致,否则报错:
setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key *.'
以上有valueForKey,也用了valueForKeyPath,,一般而言都可以,但是valueForKeyPath是键路径访问,demo:
添加个user类,
#import <Foundation/Foundation.h>
#import "model.h"
@interface user : NSObject
{
NSString *userName;
model *userModel; //model
}
@end
model类变化一下:userName 换成 score
main方法中测试:
NSDictionary *dic = @{@"userId":@"1",@"score":@"100"};
model *mod = [[model alloc]init];
[mod setValuesForKeysWithDictionary:dic];
user *use = [[user alloc]init];
[use setValue:@"zs" forKey:@"userName"];
[use setValue:mod forKey:@"userModel"];
//使用键路径访问
NSString *score = [use valueForKeyPath:@"userModel.score"];
NSLog(@"use的userModel的score: %@,userId: %@",score,[use valueForKeyPath:@"userModel.userId"]);
//另一种赋值:
[use setValue:@"20" forKeyPath:@"userModel.userId"];
NSLog(@"id是多少:%@",[use valueForKeyPath:@"userModel.userId"]);
打印结果:
16:35:15.801 KVC[4400:328669] use的userModel的score: 100,userId: 1
16:35:15.801 KVC[4400:328669] id是多少:20