KVC即Key Value Coding键值编码,它提供了一种通过字符串而不是访问器间接访问或修改对象属性的机制。
1.修改/获取属性
如下通过KVC的setValue forKey对person的name属性进行了修改(即使是私有属性)并通过valueForKey获取了name属性。
#import "ViewController.h"
@interface Person : NSObject
@end
@implementation Person
{
NSString *_name;
}
@end
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person *p = [[Person alloc]init];
[p setValue:@"xiaoming" forKey:@"name"];
NSLog(@"name=%@",[p valueForKey:@"name"]);
}
//打印信息
2017-02-16 [2376:681411] name=xiaoming
@end
2.KeyPath
当一个对象的属性是其他自定义类时,可以通过key获得这个自定义类,再通过key获得自定义类的某个属性,显然这样做比较麻烦,对此,KVC提供了一个解决方案,那就是键路径KeyPath。
#import "ViewController.h"
@interface OldPerson : NSObject
@property (nonatomic,copy)NSString* age;
@end
@implementation OldPerson
@end
@interface Person : NSObject
@property (strong, nonatomic) OldPerson *oldPerson;
@end
@implementation Person
{
NSString *name;
}
@end
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person *p = [[Person alloc]init];
p.oldPerson = [[OldPerson alloc]init];
[p setValue:@"100" forKeyPath:@"oldPerson.age"];
NSLog(@"age=%@",p.oldPerson.age);
}
@end
//打印信息:
2017-02-16 [2391:685170] age=100
可以看到oldPerson的age属性直接通过KeyPath:@"oldPerson.age"得到修改,注意这里是oldPerson对象的age属性,不是OldPerson。
3.KVC与字典
- (void)viewDidLoad {
[super viewDidLoad];
Dog *husky = [[Dog alloc]initWithName:@"husky" age:20 weight:30];
//模型转字典
NSDictionary *huskyDic = [husky dictionaryWithValuesForKeys:@[@"name",@"age",@"weight"]];
NSLog(@"huskyDic=%@",huskyDic);
Dog *wolfhound = [[Dog alloc]initWithName:@"wolfhound" age:50 weight:60];
NSLog(@"wolfhound_old Name=%@ age=%lu weight=%lf",wolfhound.name,wolfhound.age,wolfhound.weight);
//字典转模型
[wolfhound setValuesForKeysWithDictionary:huskyDic];
NSLog(@"wolfhound_new Name=%@ age=%lu weight=%lf",wolfhound.name,wolfhound.age,wolfhound.weight);
//打印出:
2017-02-25 huskyDic={
age = 20;
name = husky;
weight = 30;
}
2017-02-25 wolfhound_old Name=wolfhound age=50 weight=60.000000
2017-02-25 wolfhound_new Name=husky age=20 weight=30.000000
}
可以看到通过dictionaryWithValuesForKeys成功的将husky的属性转成了字典,通过setValuesForKeysWithDictionary成功的将字典转换成了对应的模型,使代码得到简化。
PS: I am xinghun who is on the road.