Runtime--Method Swizzling

2020-02-18  本文已影响0人  ffmylikes

关于OC的特性运行时,可以实现黑魔法 Method Swizzling。

实现代码举例:

+ (void)load {

    Classclz = [selfclass];


    SELoldSEL =@selector(viewDidAppear:);

    SELnewSEL =@selector(newviewffDidAppear:);


    MethodoriginalMethod =class_getInstanceMethod(clz, oldSEL);

    MethodswizzledMethod =class_getInstanceMethod(clz, newSEL);


    BOOLdidAddMethod =class_addMethod(clz,

                                       oldSEL,

                                       method_getImplementation(swizzledMethod),

                                       method_getTypeEncoding(swizzledMethod));


    if(didAddMethod) {

        class_replaceMethod(clz,

                            oldSEL,

                            method_getImplementation(originalMethod),

                            method_getTypeEncoding(originalMethod));

    }else{

        method_exchangeImplementations(originalMethod, swizzledMethod);

   }

}


- (void) newviewffDidAppear:(BOOL)animated {

    [selfnewviewDidAppear:animated];

    WRITE_PERFORMANCE

}

上一篇 下一篇

猜你喜欢

热点阅读