IOS obtains the attribute list of a class.
Instance description:
@interface DemoObject : NSObject@property (strong, nonatomic,readonly) NSString *name;@property (strong, nonatomic) NSMutableArray *dataSource;@property (copy, nonatomic) NSDictionary *product;@property (assign, atomic) NSUInteger count;@property (weak, nonatomic) DemoObject *object;@end
unsigned int count; objc_property_t *properties = class_copyPropertyList([DemoObject class], &count); for(int i = 0; i < count; i++) { objc_property_t property = properties[i]; NSLog(@"name:%s",property_getName(property)); NSLog(@"attributes:%s",property_getAttributes(property)); } free(properties);
The printed information is as follows:
14:59:16. 421 AppTest [11137: 94568] name: name
14:59:16. 422 AppTest [11137: 94568] attributes: T @ "NSString", R, N, V_name
14:59:16. 422 AppTest [11137: 94568] name: dataSource
14:59:16. 422 AppTest [11137: 94568] attributes: T @ "NSMutableArray", &, N, V_dataSource
14:59:16. 422 AppTest [11137: 94568] name: product
14:59:16. 422 AppTest [11137: 94568] attributes: T @ "NSDictionary", C, N, V_product
14:59:16. 422 AppTest [11137: 94568] name: count
14:59:16. 422 AppTest [11137: 94568] attributes: TQ, V_count
14:59:16. 422 AppTest [11137: 94568] name: object
14:59:16. 422 AppTest [11137: 94568] attributes: T @ "DemoObject", W, N, V_object
Note:
If we want to obtain a string, we need to get it through UTF8 encoding, as shown below:
NSString *name = [NSString stringWithUTF8String:property_getName(property)];NSString *attributes = [NSString stringWithUTF8String:property_getAttributes(property)];
The attribute format is fixed and separated by commas (,). Generally, it starts with T @ "type" and ends with V _. The following table describes the attributes in the middle:
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:
There are other types of Property instances that can be searched for in the Apple documentation "Property Attribute Description Examples"
Purpose:
1. when sending a network request, after receiving the data model replied by the server, we do not need to parse the json dictionary in each data model as our model class, we can use a base class to implement this function. If all models inherit this base class, it is OK. This function can be used to obtain the attribute name through the attribute list, the attribute type (the attribute type corresponds to the json model key) and then the value can be assigned.
2. serialization and deserialization of custom classes.