废话不多收,直接上代码
.m文件
#import"Object.h"
@interfaceObject()
{
NSString*_objectStr_M;
NSDictionary*_objectDic_M;
NSNumber*_objectNum_M;
}
@property(nonatomic,strong)NSString*objectStr_propertyM;
@property(nonatomic,strong)NSDictionary*objectDic_propertyM;
@property(nonatomic,strong)NSNumber*objectNum_propertyM;
@end
@implementationObject
{
NSString*objectStr_implementation;
NSDictionary*objectDic_implementation;
NSNumber*objectNum_M;
}
-(instancetype)init
{
self=[superinit];
if(self) {
_objectNum_M=@2;
objectNum_M=@1;
objectStr_implementation=@"objectStr_implementation";
_objectStr_M=@"_objectStr_M";
_objectStr_h=@"_objectStr_h";
_objectStr_propertyh=@"__objectStr_propertyh";
_objectStr_propertyM=@"__objectStr_propertyM";
}
returnself;
}
.h文件
@interfaceObject :NSObject
{
NSString*_objectStr_h;
NSDictionary*_objectDic_h;
NSNumber*_objectNum_h;
}
@property(nonatomic,strong)NSString*objectStr_propertyh;
@property(nonatomic,strong)NSDictionary *objectDic_propertyh;
@property(nonatomic,strong)NSNumber*objectNum_propertyh;
@end
测试代码:
Object*obj=[[Objectalloc]init];
if([objvalueForKey:@"_objectNum_M"])
NSLog(@"_objectNum_M is ______%@",[obj valueForKey:@"_objectNum_M"]);
if([objvalueForKey:@"objectNum_M"])
NSLog(@"objectNum_M is *******%@",[obj valueForKey:@"objectNum_M"]);
if([objvalueForKey:@"_objectStr_M"])
NSLog(@"_objectStr_M is %@",[obj valueForKey:@"_objectStr_M"]);
if([objvalueForKey:@"_objectStr_h"])
NSLog(@"_objectStr_h is %@",[obj valueForKey:@"_objectStr_h"]);
if([objvalueForKey:@"_objectStr_propertyh"])
NSLog(@"_objectStr_propertyh is %@",[obj valueForKey:@"_objectStr_propertyh"]);
if([objvalueForKey:@"_objectStr_propertyM"])
NSLog(@"_objectStr_propertyM is %@",[obj valueForKey:@"_objectStr_propertyM"]);
打印结果:
2016-09-08 23:17:17.759 PopMenu[2743:737039] _objectNum_M is ______2
2016-09-08 23:17:17.759 PopMenu[2743:737039] objectNum_M is *******2
2016-09-08 23:17:17.760 PopMenu[2743:737039] _objectStr_M is _objectStr_M
2016-09-08 23:17:17.760 PopMenu[2743:737039] _objectStr_h is _objectStr_h
2016-09-08 23:17:17.760 PopMenu[2743:737039] _objectStr_propertyh is __objectStr_propertyh
2016-09-08 23:17:17.760 PopMenu[2743:737039] _objectStr_propertyM is __objectStr_propertyM
可是这两句出了问题
2016-09-08 23:17:17.759 PopMenu[2743:737039] _objectNum_M is ______2
2016-09-08 23:17:17.759 PopMenu[2743:737039] objectNum_M is *******2
一开始猜想是_objectNum_M 系统认为是同一变量,但编译器不报错,于是加了一句
这就证明 KVC可以获取所有成员变量和属性的指针
if([objvalueForKey:@"objectStr_implementation"])
NSLog(@"objectStr_implementation is %@",[objvalueForKey:@"objectStr_implementation"]);
发现 2016-09-08 23:17:17.759 PopMenu[2743:737039] objectStr_implementation is objectStr_implementation
猜想错误,于是又猜 系统认为_objectNum_M ,objectNum_M是同一变量,于是交换_objectNum_M,objectNum_M 在+(void)init方法里的赋值顺序,结果还是一样,于是又猜,可能是 _objectNum_M 声明interfaceObject(),objectNum_M 声明在implementationObject里面,优先级不一样,可是结果还是一样,这就证明系统在kvc取值时,_XXX 变量 优先级>XXX 变量。这个测试还证明了KVC 权限很高,可以取所有成员和属性的指针。如果用下面这种方式声名,则不能访问: