Runtime property_getAttributes

819 阅读1分钟

Demo 测试

@interface Person : NSObject
@property (nonatomic, strong) NSString* name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy)  NSString *nickName;
- (void)test;
@end

@implementation Person

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        unsigned int outCount;
        objc_property_t *properties = class_copyPropertyList(Person.class, &outCount);
        for (int i=0; i<outCount; i++) {
            const char *name= property_getName(properties[i]);
            const char *attributes = property_getAttributes(properties[i]);
            NSLog(@"name:%s attributes:%s",name,attributes);
        }
        
    }
    return 0;
}

output:

name:name attributes:T@"NSString",&,N,V_name
name:age attributes:Tq,N,V_age
name:nickName attributes:T@"NSString",C,N,V_nickName

T@"NSString": 类型是 NSString &: retain 或者 strong N: nonatomic V_name: 在属性名字前面添加了V

Property Type String

You can use the property_getAttributes function to discover the name, the @encode type string of a property, and other attributes of the property.

The string starts with a T followed by the @encode type and a comma, and finishes with a V followed by the name of the backing instance variable. Between these, the attributes are specified by the following descriptors, separated by commas:

CodeMeaning
RThe property is read-only (readonly).
CThe property is a copy of the value last assigned (copy)
&The property is a reference
     to the value last assigned (retain).            |

| N | The property is non-atomic (nonatomic). | | G | The property defines a custom getter selector name. The name follows the G (for example, GcustomGetter,). | | S | The property defines a custom setter selector name. The name follows the S (for example, ScustomSetter:,). | | D | The property is dynamic (@dynamic). | | W | The property is a weak reference (__weak). | | P | The property is eligible for garbage collection.t Specifies the type using old-style encoding. |

ocrtPropertyIntrospection