runtime之反射机制

2018-03-09  本文已影响0人  GoldenChan

以下是JsonModel核心思想,利用runtime的反射机制,获取对应的属性名称和类型,再将对应的json序列化的 字典中响应的值赋给对象属性

基本步骤如下

1.通过调用自身的class方法获取当前类的元数据信息

2.通过runtime的 class_copyPropertyList 方法取得当前类的属性列表,以指针数组的形式返回

3.遍历指针数组,通过property_getName获取属性名,property_getAttributes获取属性类型

4.使用NSScanner来扫描属性类型字符串,将类似如下的形式"T@"NSNumber",&,N,V_id",处理成NSNumber,逐个属性循环处理

5.将所有处理好的数据放入propertyIndex这个字典中

6.通过objc_setAssociatedObject将这些数据关联到kClassPropertiesKey

Class class = [self class]; 

 NSScanner* scanner =nil;

unsigned int propertyCount; 

//获取属性列表

 objc_property_t *properties = class_copyPropertyList(class,&propertyCount);

//loop over the class properties

for(unsigned int i =0; i < propertyCount; i++) { 

//get property name获取属性名称

objc_property_t property = properties[I];

const char *propertyName = property_getName(property); 

 NSString *propertyName= [NSString stringWithUTF8String:propertyName];

//get property attributes获取属性类型

const char*attrs = property_getAttributes(property);

NSString* propertyAttributes = [NSString stringWithUTF8String:attrs];

if([propertyAttributes hasPrefix:@"Tc,"]) {

//mask BOOLs as structs so they can have custom convertors

NSString *structName= @"BOOL"; 

 } 

 scanner = [NSScanner scannerWithString: propertyAttributes];

//JMLog(@"attr: %@", [NSString stringWithCString:attrs encoding:NSUTF8StringEncoding]);

[scanner scanUpToString:@"T"intoString:nil]; 

 [scanner scanString:@"T"intoString:nil];

···

}

//finally store the property index in the static property index

objc_setAssociatedObject(self.class, 

                                              &kClassPropertiesKey,

                                               [propertyIndex copy], 

                                               OBJC_ASSOCIATION_RETAIN// This is atomic

                                                );

上一篇 下一篇

猜你喜欢

热点阅读