热修复=Runtime+Javascriptcore

通过运行时Runtime与Javascriptcore来实现热修复

Posted by Ted on April 30, 2017

一、运行时

热修复的基本原理就是Runtime运行时的方法替换,主要是下列几个方法

class_replaceMethod:方法替换

method_exchangeImplementations:IMP交换

实例,当我们要对某个类的old_method方法以new_method方法替换掉,则新建一个Category,在其load类方法(Load方法每次APP加载都会调用)中实现以下:

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        
        SEL originalSelector = @selector(old_method);
        SEL swizzledSelector = @selector(new_method);
        
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
        
        
        BOOL didAddMethod =
        class_addMethod(class,
                        originalSelector,
                        method_getImplementation(swizzledMethod),
                        method_getTypeEncoding(swizzledMethod));
        
        if (didAddMethod) {
            class_replaceMethod(class,
                                swizzledSelector,
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });

二、Javascriptcore

Javascriptcore是一个iOS原生框架,用于javascript与Objecive C语言进行相互调用,而我们热修改需要用到的就是javascript可以调用OC方法

三、热修复