KVC即Key Value Coding鍵值編碼,它提供了一種通過(guò)字符串而不是訪問(wèn)器間接訪問(wèn)或修改對(duì)象屬性的機(jī)制。
1.修改/獲取屬性
如下通過(guò)KVC的setValue forKey對(duì)person的name屬性進(jìn)行了修改(即使是私有屬性)并通過(guò)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
當(dāng)一個(gè)對(duì)象的屬性是其他自定義類時(shí),可以通過(guò)key獲得這個(gè)自定義類,再通過(guò)key獲得自定義類的某個(gè)屬性,顯然這樣做比較麻煩,對(duì)此,KVC提供了一個(gè)解決方案,那就是鍵路徑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屬性直接通過(guò)KeyPath:@"oldPerson.age"得到修改,注意這里是oldPerson對(duì)象的age屬性,不是OldPerson。
3.KVC與字典
- (void)viewDidLoad {
[super viewDidLoad];
Dog *husky = [[Dog alloc]initWithName:@"husky" age:20 weight:30];
//模型轉(zhuǎn)字典
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);
//字典轉(zhuǎn)模型
[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
}
可以看到通過(guò)dictionaryWithValuesForKeys成功的將husky的屬性轉(zhuǎn)成了字典,通過(guò)setValuesForKeysWithDictionary成功的將字典轉(zhuǎn)換成了對(duì)應(yīng)的模型,使代碼得到簡(jiǎn)化。
PS: I am xinghun who is on the road.