Runtime 知识点整理

runtime基础知识

runtime 运行时是OC的底层代码实现。我们写的OC代码底层都是基于它实现的。运行时就是IMP(方法)动态查找的过程。

OC的方法调用,实际上是objc_msgSend函数的调用,其执行大致可以分为三部分:

  • 消息发送:
    1️⃣判断消息接受者是否为nil,是则return,否继续往下执行
    2️⃣通过isa指针找到该类
    3️⃣先从类的缓存中查找IMP,如果未找到,前往类的方法列表中查找(IMP执行后缓存于类缓存中)。如果仍未找到,向下执行。
    4️⃣通过superclass寻找父类。
    5️⃣通过父类寻找IMP,同③中查找过程。
    6️⃣循环④、⑤,直至找到,或查找至元类为止。
    7️⃣执行完⑥仍未找到,执行动态方法解析。

  • 动态方法解析

  • 消息转发

IMP:
是一个函数指针,这个被指向的函数包含一个接收消息的对象(id类型,self指针),调用方法的选标SEL(方法名),以及一个不定个数的方法参数,并返回一个id类型对象。
也就是说IMP是消息最终调用的执行代码,是方法真正实现的代码。

IMP查找过程:
1、首先去该类的cache中查找,找到就返回它。
2、没找到则去该类的方法列表中查找,找到了就返回IMP,并将其加入到cache中缓存 起来。
3、如果在自己的cache和方法列表以及父类中均未找到对应的IMP,则看是不是可以进行方法决议(方法解析)。
4、如果动态方法决议(动态方法解析)不能解决问题,则进入消息转发流程。

runtime可以做的事情

苹果并不建议开发者直接使用runtime代码。但runtime代码确实可以帮助开发者实现很多OC代码难以直接实现的功能。其次来说,其执行效率也会提高。

导入头文件<objc/message.h>默认也会导入<objc/runtime.h>
#import <objc/message.h>
此时使用会有编译错误,应关闭消息发送的严格审查。配置文件设置如下:
运行时代码检查编译设为NO

Runtime 查看编译后的C代码:
cd + 文件路径
clang -rewrite-objc + (文件名)main.m
然后可以在文件目录下找到 .cpp 文件打开查看

1、消息发送

KYPerson *p = [[KYPerson alloc] init];
// 发送消息的方式调用p的方法
objc_msgSend(p, @selector(sleep));
objc_msgSend(p, @selector(eat:), @"香蕉?");
objc_msgSend(p, @selector(runWith:partner:), @"张三", @"李四");
// 方法选择器调用
[p performSelector:@selector(sleep)];
[p performSelector:@selector(eat:) withObject:@"苹果?"];
[p performSelector:@selector(runWith:partner:) withObject:@"王五" withObject:@"老六"];
// 延迟调用
[p performSelector:@selector(eat:) withObject:@"等会吃橘子?" afterDelay:2];

2、动态方法决议(动态方法解析)

消息发送,未找到相关实现方法时,会执行动态方法决议。
动态方法决议,一个是实例方法决议,一个是类方法决议。分别对应下方的两个方法:

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    NSLog(@"%s", __func__);
    return [super resolveInstanceMethod:sel];
}
+ (BOOL)resolveClassMethod:(SEL)sel {
    NSLog(@"%s", __func__);
    return [super resolveClassMethod:sel];
}
2.1实例方法决议

实例方法决议,对应的是被调用的实例方法IMP未被找到时,会调用该方法。
该方法内可以动态添加方法实现:

// 实例方法解析
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    if (sel == @selector(play)) {
        /*
         第一种,添加C方法
         return class_addMethod(self, sel, (IMP)play, "v@:");
         */
        // 第二种添加OC方法
        Method playMethod = class_getInstanceMethod(self, @selector(play));
        IMP playIMP = method_getImplementation(playMethod);
        const char * types = method_getTypeEncoding(playMethod);
        NSLog(@"%s", types);  // 打印的类型是 v16@0:8
        return class_addMethod(self, sel, playIMP, types);
    }
    NSLog(@"%s", __func__);
    return [super resolveInstanceMethod:sel];
}
// C函数
void play() {
    NSLog(@"%s", __func__);
}
2.2类方法决议

同理,类方法IMP找不到时,也会尝试进行类方法决议:

+ (BOOL)resolveClassMethod:(SEL)sel {
    if (sel == @selector(play)) {
        /* 与实例方法解析不同的是,向类发送消息,会从元类上找该方法,
            所以与实例方法解析不同的是,将第一个参数改为元类 object_getClass(self)
            另一种方法就是直接使用 class_getClassMethod
            Method playMethod = class_getClassMethod(self, @selector(play));
         */
        Method playMethod = class_getInstanceMethod(object_getClass(self), @selector(play));
        IMP playIMP = method_getImplementation(playMethod);
        const char * types = method_getTypeEncoding(playMethod);
        NSLog(@"%s", types);  // 打印的类型是 v16@0:8
        return class_addMethod(object_getClass(self), sel, playIMP, types);
    }
    NSLog(@"%s", __func__);
    return [super resolveClassMethod:sel];
}

方法class_getInstanceMethodclass_getClassMethod,将参数改为元类后效果一样。原因如下源码截图:
runtime源码截图

3、消息转发

在动态方法决议无法解决后,会执行消息转发流程。消息转发分为实例方法转发和类方法转发(大同小异)。
其方法调用流程如下依次执行:

// 转发处理(或类方法转发“-”改为“+”)
- (id)forwardingTargetForSelector:(SEL)aSelector {
    NSLog(@"%s", __func__);
    return [super forwardingTargetForSelector:aSelector];
}
// 上一方法无法处理时,执行方法注册
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    NSLog(@"%s", __func__);
    return [super methodSignatureForSelector:aSelector];
}
// 注册完成后,继续执行转发(或类方法转发“-”改为“+”)
- (void)forwardInvocation:(NSInvocation *)anInvocation {
    NSLog(@"%s", __func__);
    return [super forwardInvocation:anInvocation];
}
3.1 实例方法转发

当调用某类的某实例方法时,若该方法并不存在,则可以将该实例方法转发给其它类的实例方法去执行:

- (id)forwardingTargetForSelector:(SEL)aSelector {
    if (aSelector == @selector(play)) {
    	// 将本类的play方法,转发给KYDog去执行 [[[KYDog alloc] init] play];
    	// 类方法转发时,return [KYDog class];
        return [[KYDog alloc] init];
    }
    NSLog(@"%s", __func__);
    return [super forwardingTargetForSelector:aSelector];
}

上一步转发不能处理,则进入方法注册函数,注册完成后走下一个转发函数:

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    if (aSelector == @selector(play)) {
        return [NSMethodSignature signatureWithObjCTypes:"v@:"];
    }
    NSLog(@"%s", __func__);
    return [super methodSignatureForSelector:aSelector];
}

上一步需要注册方法,还有一次消息转发的机会:

- (void)forwardInvocation:(NSInvocation *)anInvocation {
	// 修改 anInvocation 的属性值
    anInvocation.selector = @selector(shopping);
    NSLog(@"%s", __func__);
    [anInvocation invoke];
}
3.2 类方法转发

类方法的转发,基本同上,略过 … …

4、其它功能实现

4.1 交换类方法

类方法交换,在+load方法中拿到需要交换的两个类方法,类方法内部不用做修改。在+load方法中交换,是因为其加载时机在main函数之前,且仅加载一次。

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 交换类方法
        Method class_method_1 = class_getClassMethod(self, @selector(classMethod_1:));
        Method class_method_2 = class_getClassMethod(self, @selector(classMethod_2:));
        method_exchangeImplementations(class_method_2, class_method_1);
        // 更严谨一些的可以使用 class_addMethod,防止被交还的方法不存在
    });
}
4.2 交换实例方法

实例方法的交换和类方法交换基本一致,唯一不同的是获取类方法改为获取实例方法:

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
	    // 交换实例方法
	    Method instance_method_1 = class_getInstanceMethod(self, @selector(instanceMethod_1:));
	    Method instance_method_2 = class_getInstanceMethod(self, @selector(instanceMethod_2:));
	    method_exchangeImplementations(instance_method_1, instance_method_2);
    });
}

5、获取实例变量、成员变量

5.1 获取实例变量
    KYPerson *p = [[KYPerson alloc] init];
    unsigned int count = 0;
    objc_property_t *propertys = class_copyPropertyList([p class], &count);
    for (int i=0; i<count; i++) {
        objc_property_t property = propertys[i];
        const char *name = property_getName(property);
        const char *type = property_getAttributes(property);
        NSLog(@"propertys 遍历的属性 ---> %s, 类型 ---> %s", name, type);
    }
    free(propertys);

该方法不能获取到成员变量。

5.2 获取成员变量
    KYPerson *p = [[KYPerson alloc] init];
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([p class], &count);
    for (int i=0; i<count; i++) {
        Ivar ivar = ivars[i];
        const char *name = ivar_getName(ivar);
        const char *type = ivar_getTypeEncoding(ivar);
        NSLog(@"ivar 遍历的属性 ---> %s, 类型 ---> %s", name, type);
    }
    free(ivars);

需要说明的是,该方法可以获取Extension扩展的属性但是不能获取Category添加的属性。因为ivars是拿到的成员变量,而Category不会为属性自动生成成员变量。

5.3 获取某实例代理的协议
    KYPerson *p = [[KYPerson alloc] init];
    p.delegate = self;
    unsigned int count = 0;
    Protocol * __unsafe_unretained *pros = class_copyProtocolList([self class], &count);
    for (int i = 0; i < count; i++) {
        Protocol *pro = pros[i];
        const char *name = protocol_getName(pro);
        NSLog(@"p 遍历的协议 ---> %s", name);
    }
    free(pros);
5.4 获取方法

该方法只能获取实例方法,不能获取到类方法

    KYAnimal *p = [[KYPerson alloc] init];
    unsigned int count = 0;
    // 获取的实例方法
    Method *allMethods = class_copyMethodList([p class], &count);

    for (int i = 0; i < count; i++) {
        Method method = allMethods[i];
        NSString *methodName = NSStringFromSelector(method_getName(method));
        const char * type = method_getTypeEncoding(method);
        NSLog(@"runtime 获取属性方法名 ---> %@, 类型 ---> %s", methodName, type);
    }
5.5 获取类中加载的对象
    unsigned int count = 0;
    Class *classes = objc_copyClassList(&count);
    for (int i=0; i<count; i++) {
        const char *name = class_getName(classes[i]);
        printf("%s\n", name);
    }
5.6 类别中添加属性

Category中添加的属性不会自动生成gettersetter方法,所以需要用到运行时添加关联。

@interface KYPerson()
/** 类别中添加属性 */
@property (nonatomic, strong) NSString *work;
@end

@implementation KYPerson (KYCategory)
- (void)setHome:(KYPerson *)home {
    objc_setAssociatedObject(self, @"home", home, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (KYPerson *)home {
    return objc_getAssociatedObject(self, @"home");
}
@end
5.7 动态添加方法(方法的懒加载)

动态添加方法,需要了解一下动态方法决议resolveInstanceMethod:resolveClassMethod)。
当一个对象收到一个消息,会向它独立的chahe和方法列表中以及它的父类cahce和方法列表中依次查找SEL对应的IMP。若未找到,则会crash,但若实现了resolveInstanceMethodresolveClassMethod),则可以在该方法中判断,添加未实现的方法。
调用一个实例person中未声明也未实现的实例方法:

    KYPerson *p = [[KYPerson alloc] init];
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
    [p performSelector:@selector(unrealizedInstanceMethod:) withObject:@"未实现实例方法的参数"];
    objc_msgSend(p, @selector(unrealizedInstanceMethod:), @"发送消息实现的参数");
#pragma clang diagnostic pop

KYPerson类中,实现动态方法决议:

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    NSLog(@"未实现的实例方法 ---> %@", NSStringFromSelector(sel));
    if (sel == NSSelectorFromString(@"unrealizedInstanceMethod:")) {
    	// 将要添加的c方法IMP指针传递给class_addMethod函数
        class_addMethod(self, sel, (IMP)c_method, "");
    }
    return [super resolveInstanceMethod:sel];
}

动态添加的C函数:

void c_method(id self, SEL _cmd, NSString *param) {
    NSLog(@"使用 C 函数动态添加的方法 ---> %@", param);
}

在未实现消息转发,而又未在该方法中实现selector对应的方法时,还是会崩掉。

5.8 动态创建一个类

使用runtime动态的创建出一个KYDog类,并为这个类添加一个bark:方法:

    // 创建一个KYDog类
    Class MyClass = objc_allocateClassPair([NSObject class], @"KYDog".UTF8String, 0);
    // 添加实例变量
    class_addIvar(MyClass, "属性名".UTF8String, sizeof(id), log2(sizeof(id)), @encode(id));
    // 给类添加一个属性,必须在类注册前添加属性,否则添加失败
    BOOL isSuccess = class_addIvar([MyClass class], [@"master" UTF8String], sizeof(id), log2(sizeof(id)), "@");
    // 注册创建的类
    objc_registerClassPair(MyClass);
    // 添加狗吠的方法
    class_addMethod(MyClass, @selector(bark:), bark, "");
    
    // 测试
    id dog = objc_msgSend(objc_getClass("KYDog"),sel_registerName("alloc"),sel_registerName("init"));
    objc_msgSend(dog, @selector(bark:), @"汪汪叫");
    //从类中获取成员变量Ivar
    Ivar nameIvar = class_getInstanceVariable([dog class], "master");
    //为dog的成员变量赋值
    object_setIvar(dog, nameIvar, @"鹏哥");

添加的方法使用C函数实现:

/** 动态创建类添加的方法 */
void bark(id self, SEL _cmd, NSString *param) {
    NSLog(@"狗?在叫 ---> %@", param);
}

给类添加属性时,要在注册之前添加,否则添加失败!

6、归档、解档实现

动态获取属性归档、解档:

// 归档
- (void)encodeWithCoder:(NSCoder *)aCoder {
   unsigned int count = 0;
   Ivar *ivars = class_copyIvarList([Person class], &count);
   for (int i = 0; i < count; i++) {
       Ivar ivar = ivars[i];
       const char *name = ivar_getName(ivar);
       NSString *key = [NSString stringWithUTF8String:name];
       // 归档
       [aCoder encodeObject:[self valueForKey:key] forKey:key];
   }
   free(ivars);
}
// 解档
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
  if (self = [super init]) {
      unsigned int count = 0;
      Ivar *ivars = class_copyIvarList([Person class], &count);
      for (int i = 0; i < count; i++) {
          Ivar ivar = ivars[i];
          const char *name = ivar_getName(ivar);
          NSString *key = [NSString stringWithUTF8String:name];
          // 解档
          id value = [aDecoder decodeObjectForKey:key];
          [self setValue:value forKey:key];
      }
      free(ivars);
  }
  return self;
}

一个查看消息流程的方法:
1️⃣声明一个C函数:

extern void instrumentObjcMessageSends(BOOL)

2️⃣调用该C函数:

		instrumentObjcMessageSends(YES);
        KYPerson *p = [[KYPerson alloc] init];
        [p play];
        instrumentObjcMessageSends(NO);

3️⃣调试文件路径:/private/tmp/msgSend-xxx
4️⃣进入调试文件目录,打开调试文件:
cd + /private/tmp
open msgSend-xxx





附Runtime的一些方法


// 1.objc_xxx 系列函数
// 函数名称     函数作用
objc_getClass     获取Class对象
objc_getMetaClass     获取MetaClass对象
objc_allocateClassPair     分配空间,创建类(仅在 创建之后,注册之前 能够添加成员变量)
objc_registerClassPair     注册一个类(注册后方可使用该类创建对象)
objc_disposeClassPair     注销某个类
objc_allocateProtocol     开辟空间创建协议
objc_registerProtocol     注册一个协议
objc_constructInstance     构造一个实例对象(ARC下无效)
objc_destructInstance     析构一个实例对象(ARC下无效)
objc_setAssociatedObject     为实例对象关联对象
objc_getAssociatedObje*ct     获取实例对象的关联对象
objc_removeAssociatedObjects     清空实例对象的所有关联对象


objc_系列函数关注于宏观使用,如类与协议的空间分配,注册,注销等操作

// 2.class_xxx 系列函数
函数名称     函数作用
class_addIvar     为类添加实例变量
class_addProperty     为类添加属性
class_addMethod     为类添加方法
class_addProtocol     为类遵循协议
class_replaceMethod     替换类某方法的实现
class_getName     获取类名
class_isMetaClass     判断是否为元类
objc_getProtocol     获取某个协议
objc_copyProtocolList     拷贝在运行时中注册过的协议列表
class_getSuperclass     获取某类的父类
class_setSuperclass     设置某类的父类
class_getProperty     获取某类的属性
class_getInstanceVariable     获取实例变量
class_getClassVariable     获取类变量
class_getInstanceMethod     获取实例方法
class_getClassMethod     获取类方法
class_getMethodImplementation     获取方法的实现
class_getInstanceSize     获取类的实例的大小
class_respondsToSelector     判断类是否实现某方法
class_conformsToProtocol     判断类是否遵循某协议
class_createInstance     创建类的实例
class_copyIvarList     拷贝类的实例变量列表
class_copyMethodList     拷贝类的方法列表
class_copyProtocolList     拷贝类遵循的协议列表
class_copyPropertyList     拷贝类的属性列表

-

class_系列函数关注于类的内部,如实例变量,属性,方法,协议等相关问题

// 3.object_xxx 系列函数
函数名称     函数作用
object_copy     对象copy(ARC无效)
object_dispose     对象释放(ARC无效)
object_getClassName     获取对象的类名
object_getClass     获取对象的Class
object_setClass     设置对象的Class
object_getIvar     获取对象中实例变量的值
object_setIvar     设置对象中实例变量的值
object_getInstanceVariable     获取对象中实例变量的值 (ARC中无效,使用object_getIvar)
object_setInstanceVariable     设置对象中实例变量的值 (ARC中无效,使用object_setIvar)

-

objcet_系列函数关注于对象的角度,如实例变量

// 4.method_xxx 系列函数
函数名称     函数作用
method_getName     获取方法名
method_getImplementation     获取方法的实现
method_getTypeEncoding     获取方法的类型编码
method_getNumberOfArguments     获取方法的参数个数
method_copyReturnType     拷贝方法的返回类型
method_getReturnType     获取方法的返回类型
method_copyArgumentType     拷贝方法的参数类型
method_getArgumentType     获取方法的参数类型
method_getDescription     获取方法的描述
method_setImplementation     设置方法的实现
method_exchangeImplementations     替换方法的实现

-

method_系列函数关注于方法内部,如果方法的参数及返回值类型和方法的实现

// 5.property_xxx 系列函数
函数名称     函数作用
property_getName     获取属性名
property_getAttributes     获取属性的特性列表
property_copyAttributeList     拷贝属性的特性列表
property_copyAttributeValue     拷贝属性中某特性的值

-

property_系类函数关注与属性*内部,如属性的特性等

// 6.protocol_xxx 系列函数
函数名称     函数作用
protocol_conformsToProtocol     判断一个协议是否遵循另一个协议
protocol_isEqual     判断两个协议是否一致
protocol_getName     获取协议名称
protocol_copyPropertyList     拷贝协议的属性列表
protocol_copyProtocolList     拷贝某协议所遵循的协议列表
protocol_copyMethodDescriptionList     拷贝协议的方法列表
protocol_addProtocol     为一个协议遵循另一协议
protocol_addProperty     为协议添加属性
protocol_getProperty     获取协议中的某个属性
protocol_addMethodDescription     为协议添加方法描述
protocol_getMethodDescription     获取协议中某方法的描述

// 7.ivar_xxx 系列函数
函数名称     函数作用
ivar_getName     获取Ivar名称
ivar_getTypeEncoding     获取类型编码
ivar_getOffset     获取偏移量

// 8.sel_xxx 系列函数
函数名称     函数作用
sel_getName     获取名称
sel_getUid     注册方法
sel_registerName     注册方法
sel_isEqual     判断方法是否相等

// 9.imp_xxx 系列函数
函数名称     函数作用
imp_implementationWithBlock     通过代码块创建IMP
imp_getBlock     获取函数指针中的代码块
imp_removeBlock     移除IMP中的代码块

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值