最近一段时间在研究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: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不写。