XZ_iOS之Runtime使用运行时获取类的属性列表

来源:互联网 发布:js 检测div大小变化 编辑:程序博客网 时间:2024/05/29 15:06
简介
运行时是一种面向对象的编程语言的运行环境。类似于Java的虚拟机;
OC最主要的特点就是在程序运行时,以发送消息的方式调用方法;
运行时是OC的核心,Objective-C就是基于运行时的;
参考文档:http://nshipster.cn/swift-objc-runtime/

利用 clang 生成中间代码
进入终端,输入以下命令:
$ clang -rewrite-objc main.m
可以将OC的代码重写成C++的代码

一、使用Runtime获取类的属性列表
创建一个Person类,获取这个类的属性
XZPerson.h中:
#import<Foundation/Foundation.h>

@interface XZPerson :NSObject

@property (nonatomic,copy)NSString *name;
@property (nonatomic,assign)int age;
@property (nonatomic,assign)int weight;

@end

创建一个NSObject的分类Runtime,用来获取Person类的属性列表
#import<Foundation/Foundation.h>
NSObject+XZRuntime.h中:
@interface NSObject (XZRuntime)
//获取类的属性列表
// @return类的属性列表数组
+ (NSArray *)xz_objcProperties;

@end

NSObject+XZRuntime.m中:
#import"NSObject+XZRuntime.h"
#import<objc/runtime.h>

@implementation NSObject (XZRuntime)

+ (NSArray *)xz_objcProperties {
   // class_copyIvarList  Ivar成员变量
   // class_copyPropertyList  Property属性
   // class_copyMethodList  Method方法
   // class_copyProtocolList  Protocol协议
   //参数一:要获取的类参数二:类属性的个数指针
   //返回值:所有属性的'数组'C语言中,数组的名字,就是指向第一个元素的地址
   unsignedint outCount =0;
   //调用运行时方法,取得类的属性列表
   objc_property_t *proList =class_copyPropertyList([selfclass], &outCount);
   NSLog(@"属性列表的数量 %d",outCount);
   
   NSMutableArray *array = [NSMutableArrayarray];
   //遍历所有的属性
   for (unsignedint i =0; i < outCount; i++) {
       //1.从数组中取得属性 C语言的结构体指针,通常不需要'*'
       objc_property_t pty = proList[i];
       
       // 2.pty中获得属性的名称
       constchar *cName =property_getName(pty);
       //C语言字符串转化成OC字符串
       NSString *name = [NSStringstringWithCString:cNameencoding:NSUTF8StringEncoding];
       // 3.属性名称添加到数组
        [arrayaddObject:name];
    }
   
   // retain/create/copy需要 release,点击option + click查看
   //释放数组
   free(proList);
   return array.copy;
}

XZRunTimeController.m中:
#import"XZPerson.h"
#import"NSObject+XZRuntime.h"
 //目标:获取属性数组
   NSArray *personProperties = [XZPersonxz_objcProperties];
   NSLog(@"%@",personProperties);



原创粉丝点击