一、KVC-API
KVC的全称是Key-Value Coding,俗称“键值编码”,可以通过一个key来访问某个属性,常见的API有
- (void)setValue:(id)value forKey:(NSString *)key
- (void)setValue:(id)value forKeyPath:(NSString *)keyPath
- (id)valueForKeyPath:(NSString *)keyPath;
- (id)valueForKey:(NSString *)key;
- (id)valueForUndefinedKey:(NSString *)key
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
对此api的使用不做讲解
二、setValue:forKey原理
-----------------------外面方法调用的时候-------------------
MJPerson * objc = [[MJPerson alloc]init];
[objc setValue:@(10) forKey:@"age"];
--------------------MJPerson.m文件---------------------------
#import "MJPerson.h"
@implementation MJPerson
- (void)setAge:(NSInteger)age {
NSLog(@"调用1>>>%d", age);
}
- (void)_setAge:(NSInteger)age {
NSLog(@"调用2>>>%d",age);
}
+ (BOOL)accessInstanceVariablesDirectly {
return YES;
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
NSLog(@"调用了>>>>%@>>>>%@", key, value);
}
@end
--------------------MJPerson.h文件---------------------------
@interface MJPerson : NSObject
{
@public
NSInteger _age;
NSInteger age;
NSInteger isAge;
NSInteger _isAge;
}
@end
三、valueForKey:原理
代码如下(示例):
-----------------------外面方法调用的时候-------------------
MJPerson * objc = [[MJPerson alloc]init];
[objc setValue:@(10) forKey:@"age"];
--------------------MJPerson.m文件---------------------------
#import "MJPerson.h"
@implementation MJPerson
- (int)getAge {
return 10;
}
- (int)age {
return 11;
}
- (int)isAge {
return 12;
}
- (int)_age {
return 13;
}
+ (BOOL)accessInstanceVariablesDirectly {
return YES;
}
- (id)valueForUndefinedKey:(NSString *)key {
NSLog(@"找不到key>>>>%@",key);
return @"";
}
@end
--------------------MJPerson.h文件---------------------------
@interface MJPerson : NSObject
{
@public
NSInteger _age;
NSInteger age;
NSInteger isAge;
NSInteger _isAge;
}
@end
通过KVC修改成员变量的属性,会触发KVO 内部相当于这样执行 [person willChangeValueForKey:@“age”]; person->_age = 10; [person didChangeValueForKey:@“age”];
|