美文网首页
runtime之反射机制

runtime之反射机制

作者: GoldenChan | 来源:发表于2018-03-09 15:46 被阅读0次

以下是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

                                                );

相关文章

  • runtime之反射机制

    以下是JsonModel核心思想,利用runtime的反射机制,获取对应的属性名称和类型,再将对应的json序列化...

  • Java基础之反射

    Java基础之—反射(非常重要)Java中反射机制详解Java进阶之reflection(反射机制)——反射概念与...

  • Java反射

    Java反射 概述 Java反射机制可以让我们在编译期(Compile Time)之外的运行期(Runtime)检...

  • 注解使用

    一、Runtime 在运行时(Runtime)通过反射机制运行处理的注解 二、Compile time 编译时(C...

  • java面试知识点(四)- java 动态代理

    java 反射 反射是一种机制,提供java 程序在RunTime获取类的元属性信息,创建对象,执行方法,修改权限...

  • Java Reflection

    简介 Java反射机制是让我们在编译期(Compile Time)之外的运行期(Runtime)检查类,接口,变量...

  • Android面试需要的那些技能[欢迎补充]

    一、了解常用的设计模式,数据结构和算法;二、精通Java基础,理解Java的runtime机制,熟悉Java反射,...

  • Runtime那些事儿(消息机制)

    Runtime那些事儿(消息机制) Runtime那些事儿(消息机制)

  • 利用runtime反射机制解耦

    前言 本文参考了微信读书团队的文章,学习了runtime反射机制的强大。具体的demo工程 学习过程1 A和B想要...

  • Java Reflection(反射机制)详解

    Java反射机制可以让我们在编译期(Compile Time)之外的运行期(Runtime)获得任何一个类的字节码...

网友评论

      本文标题:runtime之反射机制

      本文链接:https://www.haomeiwen.com/subject/yyapfftx.html