您的位置:首页 > 运维架构

通过OC运行时(runtime)获得类的属性列表

2015-08-12 13:39 260 查看
最近一段时间在研究OC的运行时机制,碰到一个叫property_getAttributes函数,再此对其用法进行简单的总结。 property_getAttributes主要用于获取一个类的property即该property的属性数据,也叫metadata(元数据),涉及到得运行时函数包括class_copyPropertyList,property_getName和propert_getAttributes

大体用法如下:
#import <objc/runtime.h>
......
- (void)custom{
unsigned pCount;
objc_property_t *properties=class_copyPropertyList([self class], &pCount);//属性数组
for(int i=0;i<pCount;++i){
objc_property_t property=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
@synthesize myName;
- (void)printAllAttributes{
unsigned pCount;
objc_property_t *properties=class_copyPropertyList([self class], &pCount);//属性数组
for(int i=0;i<pCount;++i){
objc_property_t property=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:myName2015-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不写。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息