runtime_04

2018-04-05  本文已影响20人  申申申申申

首先感谢祖国,可以无忧无虑的码代码 ~


If I have seen further, it is by standing on the shoudlers of giants.


Method Swizzling

首先看下Method的定义,其实是一个指向objc_method结构体的指针
具体关于SELIMPMethod的说明请参考 runtime_02

/// An opaque type that represents a method in a class definition.
typedef struct objc_method *Method;

struct objc_method {
    SEL _Nonnull method_name                                 OBJC2_UNAVAILABLE;
    char * _Nullable method_types                            OBJC2_UNAVAILABLE;
    IMP _Nonnull method_imp                                  OBJC2_UNAVAILABLE;
}                                                            OBJC2_UNAVAILABLE;

方法的SEL method_nameIMP method_imp是一一对应的,而method swizzling实现机制就是动态改变这两者的对应的关系,这样就可以动态地替换方法的实现
swizzling前:sel_A --> imp_Asel_B --> imp_B
swizzling后:sel_A --> imp_Bsel_B --> imp_A

关键性函数:

/** 
 * Replaces the implementation of a method for a given class.
 * 
 * @param cls The class you want to modify.
 * @param name A selector that identifies the method whose implementation you want to replace.
 * @param imp The new implementation for the method identified by name for the class identified by cls.
 * @param types An array of characters that describe the types of the arguments to the method. 
 *  Since the function must take at least two arguments—self and _cmd, the second and third characters
 *  must be “@:” (the first character is the return type).
 * 
 * @return The previous implementation of the method identified by \e name for the class identified by \e cls.
 * 
 * @note This function behaves in two different ways:
 *  - If the method identified by \e name does not yet exist, it is added as if \c class_addMethod were called. 
 *    The type encoding specified by \e types is used as given.
 *  - If the method identified by \e name does exist, its \c IMP is replaced as if \c method_setImplementation were called.
 *    The type encoding specified by \e types is ignored.
 */
OBJC_EXPORT IMP _Nullable
class_replaceMethod(Class _Nullable cls, SEL _Nonnull name, IMP _Nonnull imp, 
                    const char * _Nullable types) 
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
/** 
 * Replaces the implementation of a method for a given class.
 * 
 * @param cls The class you want to modify.
 * @param name A selector that identifies the method whose implementation you want to replace.
 * @param imp The new implementation for the method identified by name for the class identified by cls.
 * @param types An array of characters that describe the types of the arguments to the method. 
 *  Since the function must take at least two arguments—self and _cmd, the second and third characters
 *  must be “@:” (the first character is the return type).
 * 
 * @return The previous implementation of the method identified by \e name for the class identified by \e cls.
 * 
 * @note This function behaves in two different ways:
 *  - If the method identified by \e name does not yet exist, it is added as if \c class_addMethod were called. 
 *    The type encoding specified by \e types is used as given.
 *  - If the method identified by \e name does exist, its \c IMP is replaced as if \c method_setImplementation were called.
 *    The type encoding specified by \e types is ignored.
 */
OBJC_EXPORT IMP _Nullable
class_replaceMethod(Class _Nullable cls, SEL _Nonnull name, IMP _Nonnull imp, 
                    const char * _Nullable types) 
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

看栗子:
需要在每一个vc展示的时候,给用户提示,或者使用某些第三方进行统计等等类似操作,可以在viewWillAppear:实现
实现方式:

  1. 直接修改每个页面的viewWillAppear:
    这种做法会产生大量的重复代码,还容易遗漏某些页面,非常难于维护
  2. 创一个一个子类继承自ViewController,然后使用的vc都来继承这个类
    这个稍微好一点,但是也同样需要子类化UIViewControllerUITableViewController等不同类型的vc,但是如果新来的同事不知道这种做法呢,同样这种做法也不易于维护
  3. 比较合适的实现方法是使用method swizzling,如下
    注释比较详细
#import "FFBaseViewController+statistics.h"

@implementation FFBaseViewController (statistics)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 获取当前分类所属的类
        Class class = [self class];

        // 获取主类的 viewWillAppear,方法选择器 和 指向objc_method结构体的指针
        SEL origin_sel = @selector(viewWillAppear:);
        Method origin_method = class_getInstanceMethod(class, origin_sel);

        // 首先需要确定 swizzling_method 必须要实现,无论是在本类中实现,还是在父类中实现,还是其他什么地方
        SEL swizzling_sel = @selector(ff_viewWillAppear:);
        // class_getInstanceMethod 会去检索是否父类实现
        Method swizzling_method = class_getInstanceMethod(class, swizzling_sel);

        // class_addMethod 会重写父类的实现,但是不会替换本类的实现,如果本类中有同名实现就返回 no,如果没有就添加该方法成功后返回 yes
        // 判断当前主类中是否存在 viewWillAppear,如果没有实现就添加,并将实现置为 ff_viewWillAppear的实现
        BOOL isSucc = class_addMethod(class, origin_sel, method_getImplementation(swizzling_method), method_getTypeEncoding(swizzling_method));

        if (isSucc) { // 主类中没有实现 viewWillAppear,此时在运行时已经成功添加,但是实现是 swizzling_method 的实现
            // 由于交换后 viewWillAppear的实现 实际上为 ff_viewWillAppear的实现,此时将 ff_viewWillAppear 的实现替换为 viewWillAppear的实现
            class_replaceMethod(class, swizzling_sel, method_getImplementation(origin_method), method_getTypeEncoding(origin_method));
        } else {
            // 主类中存在同名方法的实现,此时只需要交换方法即可
            method_exchangeImplementations(origin_method, swizzling_method);
        }

        // 经过上面的操作,viewWillAppear 和 ff_viewWillAppear 的实现已经互换
        // 然后系统执行 viewWillAppear 的时候 就会执行我们想要的操作(比如统计 等)
        // 然而由于我们再 ff_viewWillAppear 的实现中显式地调用自身(如下),所以在交换后的 viewWillAppear 中 会主动调用 ff_viewWillAppear
        // 而此时 ff_viewWillAppear的实现为 viewWillAppear 原本的实现
        // 因此就可以实现 在执行我们需要的代码后,继续执行没有改变之前 viewWillAppear 中需要执行的操作,从而完成衔接
    });
}

- (void)ff_viewWillAppear:(BOOL)animated {
    // 表面看起来 在方法内部调用方法本身,会引起死循环,实际上在运行时 ff_viewWillAppear 的实现已经变成了 viewWillAppear 的实现,并不会引起无限循环
    [self ff_viewWillAppear:animated];
    // do something ...
    NSLog(@"ff_viewWillAppear ---> %s", class_getName(self.class));
}
@end

使用method swizzling的需要注意的地方:

  1. method swizzling应该在+ load中执行
    OC中,如果类实现了+ load或者 + initialize,运行时会自动调用,并且这两个方法是可选的,并且是只有实现了才会被调用
  1. method swizzling应该在dispatch_once中执行
    因为method swizzling是全局的操作,所以需要在运行时采取一定的预防措施,而原子性就正合适,可以确保代码只被执行一次,无论多少个线程GCDdispatch_once都可以确保代码只被执行一次
  2. 一定要调用修改前的实现
    如果需要替换的是系统提供的函数,那么在自己实现的方法中,应该 总是 调用方法的原始实现,因为API提供了一个输入与输出的约定,但是其内部的实现是一个黑盒,swizzling一个方法而不调用方法的原始实现可能会打破系统原本的实现,因此需要调用原本的实现,来保证内部操作的正常运行

不定期更新 不合适的地方 还请指点~ 感激不尽
愿祖国繁荣昌盛~
o(* ̄3 ̄)o

上一篇下一篇

猜你喜欢

热点阅读