获取Objc 类方法及属性的研究实现

获取Objc 类方法及属性需要涉及到runtime。
objective-c中runtime:是一套比较底层的纯C语言API, 属于1个C语言库, 包含了很多底层的C语言API。 在我们平时编写的OC代码中, 程序运行过程时, 其实最终都是转成了runtime的C语言代码。

使用runtime需要引入:

#include <objc/runtime.h>

通过类名获取类的方法列表,打印方法名

    u_int count;
    Method* methods = class_copyMethodList([UIView class], &count);
    for (int i = 0; i < count; i ++) {
        SEL name = method_getName(methods[i]);
        NSString* strName = [NSString stringWithCString:sel_getName(name) encoding:NSUTF8StringEncoding];
        NSLog(@"method: %@",strName);
    }

通过类名获取类属性列表,并打印属性名

    u_int _count;
    objc_property_t* pList = class_copyPropertyList([UIView class], &_count);
    for (int i = 0; i < _count; i ++) {
        const char* name = property_getName(pList[i]);
        NSString* strName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
        NSLog(@"preperty: %@",strName);
    }

通过ivar指针获取成员变量列表

    u_int count;
    Ivar* ivars = class_copyIvarList([UIView class], &count);
    for (const Ivar*p = ivars; p < ivars+count; ++p) {
        Ivar const ivar = *p;
        NSString* name = [NSString stringWithUTF8String:ivar_getName(ivar)];
        NSLog(@"name: %@",name);
    }
posted @ 2015-12-21 10:15  沙影无痕  阅读(473)  评论(0编辑  收藏  举报