KVC的简单使用

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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • KVC(Key-value coding)键值编码,iOS的开发中,可以允许开发者通过Key名直接访问对象的属性,...
    CALayer_Sai阅读 2,575评论 0 4
  • KVC(Key-value coding)键值编码,单看这个名字可能不太好理解。其实翻译一下就很简单了,就是指iO...
    朽木自雕也阅读 1,620评论 6 1
  • KVC(Key-value coding)键值编码,单看这个名字可能不太好理解。其实翻译一下就很简单了,就是指iO...
    黑暗中的孤影阅读 50,093评论 74 441
  • KVC字典转模型 KVC 中经常使用的就是字典转模型 KVC的大招 KVC设置对象属性及取值 KVC间接设置对象属...
    冷漠叻荭颜阅读 4,841评论 0 15
  • 我想要的爱,是细水长流温柔浪漫,不是很猛烈地来的快去的也快。如果你爱我,就让我觉得你爱我吧,温柔体贴似最初追我的你...
    辛德瑞拉的小红鞋阅读 201评论 0 2