0%

Runtime获取Class属性列表及属性类型

反馈请联系hertz@hertzwang.com,谢谢

属性类型

property_getAttributes获取至的结构:数据类型,修饰词...,V_属性名称,如:T@,R,C,N,V_idValue

  • 数据类型,以”T”开始至第一个”,”
    • @ -> id
    • @”XXX” -> XXX,如:@”NSString”、@”NSArray”
    • i -> int
    • d -> double
    • f -> float
  • 修饰词,以第一个”,”开始至最后一个”,”
    • N -> nonatomic
    • R -> reonly
    • C -> copy
    • & -> strongretain
    • W -> weak
  • V_属性名称,以"V_"开始至结尾,"V_"后面的就是属性名称

代码

  • 属性声名

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @property (nonatomic, copy, readonly, nullable) id idValue;
    @property (nonatomic, copy) NSNumber *numberValue;
    @property (nonatomic, strong) NSString *stringValue;
    @property (nonatomic, copy) NSArray *arrayValue;
    @property (nonatomic, copy) NSDictionary *dictionaryValue;
    @property (nonatomic, assign) int intValue;
    @property (nonatomic, assign) double doubleValue;
    @property (nonatomic, assign) float floatValue;
    @property (nonatomic, assign, readwrite) CGFloat cgfloatValue;
    @property (nonatomic, retain) NSString *retainStringValue;
    @property (nonatomic, weak) NSString *weakStringValue;
    @property (nonatomic, strong) NSString *__weakStringValue;
  • 获取属性列表及属性类型

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    #import <objc/runtime.h>

    ...

    uint count;
    objc_property_t *propertys = class_copyPropertyList(ObjectClass.class, &count);
    @try {
    for (int i = 0; i < count; i++) {
    objc_property_t property = propertys[i];
    NSLog(@"%s -> %s", property_getName(property), property_getAttributes(property));
    }
    } @finally {
    free(propertys);
    }

  • 打印结果

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    idValue -> T@,R,C,N,V_idValue
    numberValue -> T@"NSNumber",C,N,V_numberValue
    stringValue -> T@"NSString",&,N,V_stringValue
    arrayValue -> T@"NSArray",C,N,V_arrayValue
    dictionaryValue -> T@"NSDictionary",C,N,V_dictionaryValue
    intValue -> Ti,N,V_intValue
    doubleValue -> Td,N,V_doubleValue
    floatValue -> Tf,N,V_floatValue
    cgfloatValue -> Td,N,V_cgfloatValue
    retainStringValue -> T@"NSString",&,N,V_retainStringValue
    weakStringValue -> T@"NSString",W,N,V_weakStringValue
    __weakStringValue -> T@"NSString",&,N,V___weakStringValue