kvc机制与kvc的常用方法

kvc是key value coding的缩写,即:键值编码。键值编码提供了非常强大的功能:只要存在访问器方法、声明属性或实例变量,就可以将其名字指定为字符串来访问。

// 返回表示属性的键字符串对应的值

- (id)valueForKey:(NSString *)key;

Person *p1 = [[Person alloc] init];
[p1 setValue:@"张三" forKey:@"name"];
 NSString *name = [p1 valueForKey:@"name"];


// 将键字符串key所对应的属性的值设置为value

- (void)setValue:(id)value forKey:(NSString *)key;

// p1是Person类的对象,name是Person类的一个属性
Person *p1 = [[Person alloc] init];       
[p1 setValue:@"张三" forKey:@"name"];
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// 以点“.”切分键路径,并使用第一个键像接收器发送valueForKey:方法,然后在使用路径的下一个键,向得到的对象发送valueForKey:fangfa,如此反复操作,返回最后获得的对象。

- (id)valueForKeyPath:(NSString *)keyPath;


// 与valueForKeyPath:方法同样取出对象,这里只对路径中的最后一个键调用setValue:ForKey:方法,并设置属性值为value。

- (void)setValue:(id)value forKeyPath:(NSString *)keyPath;


例:

Dog类:

@interface Dog : NSObject
// 狗的品种
@property (nonatomic, copy) NSString *name;

@end
Person类:
#import 
#import "Dog.h"
@interface Person : NSObject

// 姓名
@property (nonatomic, copy) NSString *name;

// 年龄
@property (nonatomic, assign) int age;

// 电子邮件
@property (nonatomic, copy) NSString *email;

@property (nonatomic, strong) Dog *dog;

@end
main函数:
#import 
#import "Person.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
   Person *p1 = [[Person alloc] init];
   // @"dog.name" 这个就叫做keyPath 或者叫 "属性的路径"
   [p1 setValue:@"哈士猫" forKeyPath:@"dog.name"];

 NSString *dogName = [p1 valueForKeyPath:@"dog.name"];


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// 根据字典的键,找对应的属性,为属性赋值(字典转模型

- (void)setValuesForKeysWithDictionary:(NSDictionary *)keyedValues;


#import 
#import "Person.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
   Person *p1 = [[Person alloc] init];
  NSDictionary *bz = @{
                             @"name" : @"小明",
                             @"age" : @28,
                             @"email" : @"[email protected]",
                             @"dog" : @{@"name" : @"加肥猫"}
                             };
        
   [p1 setValuesForKeysWithDictionary:bz];

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// 把对象转成字典

- (NSDictionary *)dictionaryWithValuesForKeys:(NSArray *)keys;

   // 把对象转成字典
        NSDictionary *dict = [p1 dictionaryWithValuesForKeys:@[@"name", @"age", @"email", @"dog"]];





你可能感兴趣的:(iPhone开发)