KVC 其实就是键值编码
1、赋值其实就两个方法
- setValue: forKey 给对象的某个属性值赋值
-
setValue:forKeyPath
给对象的某个属性中的属性赋值
2、获取值其实也是两个方法
-
valueForKey 获取对象的某个属性值
-
valueForKeyPath 获取对象的某个属性中的属性值
@interface Cat : NSObject @property (nonatomic,copy) NSString *name; @end @interface Person : NSObject @property (nonatomic,assign) int age; @property (nonatomic, strong) Cat *cat; @end self.p=[[Person alloc]init]; Cat *cat=[[Cat alloc]init]; self.p.cat=cat; [self.p setValue:@12 forKey:@"age"]; [self.p setValue:@"猪" forKeyPath:@"cat.name"]; NSLog(@"--%d--%@",self.p.age,self.p.cat.name);//--12--猪 NSLog(@"--%@--%@",[self.p valueForKey:@"age"],[self.p valueForKeyPath:@"cat.name"]);//--12--猪
3、setValue:forKey:的原理
4、valueForKey:的原理
self.p=[[Person alloc]init]; [self.p setValue:@12 forKey:@"age"]; #import "Person.h" @implementation Person -(void)setAge:(int)age{ NSLog(@"1"); } -(void)_setAge:(int)age{ NSLog(@"2"); } @end @interface Person : NSObject { int _age; int _isAge; int age; int isAge; } @end
---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
@implementation Person -(int)getAge{ return 1; } -(int)age{ return 2; } -(int)isAge{ return 3; } -(int)_age{ return 4; } @end .h @interface Person : NSObject { int _age; int _isAge; int age; int isAge; }