KVC:鍵值編碼
賦值有各種各樣的方式,點語法,KVC......
KVC的核心功能 : 修改類中的私有屬性
創(chuàng)建一個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);
}
創(chuàng)建一條狗
@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);
輸出結(jié)果:
self.p = 小明
age = 18
self.d = dog