iOS - 利用runtime加深对基础知识的理解

时间:2022-01-14 07:32:39

利用runtime加深对基础知识的理解

如果对runtime需要学习,可以看这篇,以下仅作为学习笔记,相互交流。

runtime的头文件:

#import <objc/runtime.h> //*> 对方法、变量、属性和类别的方法
#import <objc/message.h> //*> 消息转发的方法

1.获取OC类的变量名、属性名、方法

首先介绍三个函数:
class_copyIvarList()
class_copyPropertyList()
class_copyMethodList()
警告:使用以上三个方法没用的时候必须要free()掉。通过下面代码进行分析


/*
    首先,创建集成NSObject的Person对象,然后在Person.h写入:

    @interface People : NSObject
            @property (nonatomic, strong) NSString * name;
            @property (nonatomic, assign) BOOL Number;
    @end

    然后在AppDelegate.m写入一下代码,进行测试。

*/

    unsigned int count  = 0;
    unsigned int count2 = 0;
    unsigned int count3 = 0;

    Ivar * ivars                = class_copyIvarList([People class], &count);
    Method * methods            = class_copyMethodList([People class], &count2);
    objc_property_t * propertys = class_copyPropertyList([People class], &count3);

    for (int i = 0; i < count; i++)
    {
        Ivar ivar = ivars[i];
        const char * ivarname = ivar_getName(ivar);
        NSString * key = [NSString stringWithUTF8String:ivarname];
        NSLog(@"%@",key);
    }

    NSLog(@"\n");
    for (int i = 0; i < count3; i++)
    {
        objc_property_t property = propertys[i];
        const char * propertyname = property_getName(property);
        NSString * key = [NSString stringWithUTF8String:propertyname];
        NSLog(@"%@",key);
    }

    NSLog(@"\n");
    for (int i = 0; i< count2; i++)
    {
        Method method = methods[i];
        SEL methodname = method_getName(method);
        NSString * key = NSStringFromSelector(methodname);
        NSLog(@"%@",key);
    }
//    free(ivars);
//    free(methods);
//    free(propertys);
/*
    如果不写上面三行free(),就会出现内存泄露,如下图
*/

iOS - 利用runtime加深对基础知识的理解
iOS - 利用runtime加深对基础知识的理解

打印结果:


2016-03-23 14:39:56.167 测试1[2491:974748] _Number
2016-03-23 14:39:56.168 测试1[2491:974748] _name
2016-03-23 14:39:56.168 测试1[2491:974748]
2016-03-23 14:39:56.168 测试1[2491:974748] name
2016-03-23 14:39:56.168 测试1[2491:974748] Number
2016-03-23 14:39:56.168 测试1[2491:974748]
2016-03-23 14:39:56.169 测试1[2491:974748] Number
2016-03-23 14:39:56.169 测试1[2491:974748] .cxx_destruct
2016-03-23 14:39:56.170 测试1[2491:974748] dealloc
2016-03-23 14:39:56.170 测试1[2491:974748] name
2016-03-23 14:39:56.170 测试1[2491:974748] setName:
2016-03-23 14:39:56.170 测试1[2491:974748] init
2016-03-23 14:39:56.171 测试1[2491:974748] setNumber: