KVC:键值编码
赋值有各种各样的方式,点语法,KVC......
KVC的核心功能 : 修改类中的私有属性
创建一个Person类,私有属性_personAge
@interface Person : NSObject
{
@private
int _personAge;
}
//姓名,体重,狗
@property(nonatomic, copy) NSString *name;
@property(nonatomic,assign)int weight;
@property(nonatomic, strong) Dog *dog;
-(void)loagAge;
@end
-(void)loagAge{
NSLog(@"age = %d",_personAge);
}
创建一条狗
@interface Dog : NSObject
@property(nonatomic, copy) NSString *name;
@property(nonatomic,assign)int dogAge;
@end
简单编写:
self.p = [[Person alloc]init];
self.d = [[Dog alloc]init];
self.p.dog = self.d;
//通过KVC的方式给Person和Dog的属性赋值
//Person name
[self.p setValue:@"小明" forKeyPath:@"name"];
NSLog(@"self.p = %@",self.p.name);
//Person 私有属性_age
[self.p setValue:@18 forKeyPath:@"personAge"];
[self.p loagAge];
[self.p setValue:@"dog" forKeyPath:@"dog.name"];
NSLog(@"self.d = %@",self.d.name);
输出结果:
self.p = 小明
age = 18
self.d = dog