KVC的全称是Key-Value Coding,俗称“键值编码”,可以通过一个key来访问某个属性
常见的API有:
- (void)setValue:(id)value forKey:(NSString *)key;
- (void)setValue:(id)value forKeyPath:(NSString *)keyPath;
- (id)valueForKey:(NSString *)key;
- (id)valueForKeyPath:(NSString *)keyPath;
基本用法如下:
Cat.h文件
#import <Foundation/Foundation.h>
@interface Cat : NSObject
@property (nonatomic,assign) int weight;
@end
Person.h文件
#import <Foundation/Foundation.h>
#import "Cat.h"
@interface Person : NSObject
@property (nonatomic,assign) int age;
@property (nonatomic,strong) Cat *cat;
@end
Person *person = [[Person alloc] init];
[person setValue:@10 forKey:@"age"];
person.cat = [[Cat alloc] init];
[person setValue:@20 forKeyPath:@"cat.weight"];
NSLog(@"age = %d",person.age);
NSLog(@"weight = %d",person.cat.weight);
Person *person = [[Person alloc] init];
person.age = 10;
person.cat = [[Cat alloc] init];
person.cat.weight = 20;
NSLog(@"age = %@",[person valueForKey:@"age"]);
NSLog(@"age = %@",[person valueForKeyPath:@"age"]);
NSLog(@"weight = %@",[person valueForKeyPath:@"cat.weight"]);
setValue:forKey:的原理
accessInstanceVariablesDirectly方法的默认返回值是YES
valueForKey:的原理