美文网首页
runtime - class_replaceMethod

runtime - class_replaceMethod

作者: _RG | 来源:发表于2019-08-23 11:59 被阅读0次
// 替代方法的实现
IMP class_replaceMethod ( Class cls, SEL name, IMP imp, const char *types );

class_replaceMethod函数,该函数的行为可以分为两种:如果类中不存在name指定的方法,则类似于class_addMethod函数一样会添加方法;如果类中已存在name指定的方法,则类似于method_setImplementation一样替代原方法的实现。

注意,如果替换了父类的方法, 但是子类自己实现了父类的方法, 则子类的方法没有调用父类时, 子类的方法不会被替换

例如 一个是 UIViewController 的分类,

@implementation UIViewController (Tracking)


+ (void)load {
    Class class = [self class];

    SEL originalSelector = @selector(viewWillAppear:);
    SEL swizzledSelector = @selector(swizz_viewWillAppear:);

    // 获取实例方法
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    class_replaceMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(originalMethod));
}

-(void)swizz_viewWillAppear:(BOOL)animation
{
//    [self swizz_viewWillAppear:animation];
    
    NSLog(@"viewWillAppear-----: %@",self);
}

@end

一个是 UIViewController的子类, 如果子类 不调用父类的viewWillAppear:方法,只是调用自己的viewWillAppear, 则不会交换方法, 只有调用父类的viewWillAppear时才会交换


-(void)viewWillAppear:(BOOL)animated
{
//    [super viewWillAppear:animated];
    
    NSLog(@"=====");
}

相关文章

网友评论

      本文标题:runtime - class_replaceMethod

      本文链接:https://www.haomeiwen.com/subject/ylvzsctx.html