通过OC运行时(runtime)获得类的属性列表
最近一段时间在研究OC的运行时机制,碰到一个叫property_getAttributes函数,再此对其用法进行简单的总结。
property_getAttributes主要用于获取一个类的property即该property的属性数据,也叫metadata(元数据),涉及到得运行时函数包括class_copyPropertyList,property_getName和propert_getAttributes
大体用法如下:
#import<objc/runtime.h>......-(void)custom{unsignedpCount;objc_property_t*properties=class_copyPropertyList([selfclass],&pCount);//属性数组for(inti=0;i<pCount;++i){objc_property_tproperty=properties[i];NSLog(@"propertyName:%s",property_getName(property));NSLog(@"propertyAttributes:%s",property_getAttributes(property));}}
具体用法如下:
eg.定义了一个类CustomClass,有属性定义如下
头文件:
CustomClass.h#import<objc/runtime.h>......@property(nonatomic,strong)NSString*myName;
实现文件:
CustomClass.m@synthesizemyName;-(void)printAllAttributes{unsignedpCount;objc_property_t*properties=class_copyPropertyList([selfclass],&pCount);//属性数组for(inti=0;i<pCount;++i){objc_property_tproperty=properties[i];NSLog(@"propertyName:%s",property_getName(property));NSLog(@"propertyAttributes:%s",property_getAttributes(property));}}
最后的输出结果如下:
2015-08-12 12:56:45.147 UIMenuController[1924:146558] propertyName:myName
2015-08-12 12:56:45.147 UIMenuController[1924:146558] propertyAttributes:T@"NSString",&,N,VmyName
解释:
在上例中获得propertyAttributes为:T@"NSString",&,N,VmyName
这是一个char *类型.
T:开头字母
@"NSString":property的类型。@表示此property是OC类,"NSString"表明具体的OC类名。例如:
id myName;//@
UIColor *myName;//@"UIColor"
UITextField *myName;//@"UITextField"
CustomClass *myName;//@"CustomClass",为自定义类型
int myName;//i,即若为基本数据类型,则只是@encode(int)的值i
&:表明property为retain(strong),除此之外,C表示copy,assign没有表示。
N:表示nonatomic,若为atomic则不写。
VmyName:V开头加property名
此外,读写属性:readonly表示为R,readwrite不写。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。