方法交换安全实现

2018-02-25  本文已影响10人  王家薪
+ (void)load {
    // 这个是要交换的方法 
    Method method1 = class_getInstanceMethod([UILabel class], @selector(jx_setFont:));
    // 这个是被交换的方法
    Method method2 = class_getInstanceMethod([UILabel class], @selector(setFont:));
    // 首先想类中添加被交换的方法 如果被交换的方法是父类的并且子类没有重写这个方法, 这种情况子类方法列表中是没有被交换的方法的,这样直接交换就会将父类的方法交换掉
    // 所以首先向父类中添加被交换的方法, 如果添加失败 说明子类已经实现被交换的方法 可以放心交换了
    // 如果添加成功 则直接取代
    if (!class_addMethod([UILabel class], @selector(setFont:), method_getImplementation(method1), method_getTypeEncoding(method1))) {
        method_exchangeImplementations(method2, method1);
    } else {
        class_replaceMethod(self, @selector(jx_setFont:), method_getImplementation(method2), method_getTypeEncoding(method2));
    }
  
}
上一篇 下一篇

猜你喜欢

热点阅读