iOS runtime 初步学习

时间:2023-03-08 23:43:00
iOS runtime 初步学习

注: 在Xocde5之后, 使用运行时方法需要进行2步设置
1. 在Build Setting中搜索'msg', 设置'Strict Checking' 为 NO
2. 使用需要导入头文件 #import <objc/message.h>

// 一. 消息发送
objc_msgSend(类对象 / 实例对象, @selector(方法名:), 参数(可选));

// 二. 方法交换(以UIImage的imageNamed:方法为例)
// 1. 获取method
Method method1 = class_getClassMethod([UIImage class], @selector(imageNamed:));
Method method2 = class_getClassMethod([UIImage class], @selector(xc_imageNamed:));
// 2. 交换method
method_exchangeImplementations(method1, method2);
// xc_imageNamed: 方法实现
+ (__kindof UIImage *)xc_imageNamed:(NSString *)imageName {
    UIImage *image = [UIImage xc_imageNamed:imageName];
    if (image == nil) {
        NSLog(@"image为空-----");
    }
    return image;
}

// 三.获取成员变量名称
// 1. 定义一个无符号整型数字(用于记录类中的成员变量的个数)
unsigned int count = 0;
// 2. 使用这个runtime函数,可以获取一个类的成员变量,返回一个ivar类型的数组
Ivar *vars = class_copyIvarList([BESTNews class], &count);
for (int i = 0; i < count; i++) {
    Ivar member = vars[i];
      // 3. 输出对应的成员变量名称
    const char *name = ivar_getName(member);
    NSLog(@"%s", name);
}