使用runtime替换类中的系统方法

假如现在有一个业务需求,在项目中每个控制器界面将要显示的时候执行一段代码,可能你第一时间想到的就是新建一个基类控制器BaseViewController,然后在BaseViewController中重写viewWillAppear方法,后面的控制器都继承自这个BaseViewController,这样不是不行,只是后面新建的每一个控制器都对父类进行了修改,这样是很消耗内存和资源的一个操作,现在用runtime,交换UIViewController中的viewWillAppear方法的实现:

先附上BaseViewController中的代码:

+(void)load
{
    NSString*className=NSStringFromClass(self.class);
    NSLog(@"classname%@",className);
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        Class class =[self class];
        SEL originalSelector=@selector(viewWillAppear:);
        SEL swizzledSelector=@selector(xxx_viewWillAppear:);
        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);
        }
    });
}

-(void)xxx_viewWillAppear:(BOOL)animated
{
    NSLog(@"viewWillAppear:%@",self);
    [self xxx_viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

这段代码的作用是替换UIViewControllerviewWillAppear方法,所以以后每个页面出现的时候就会执行代码中-(void)xxx_viewWillAppear:(BOOL)animated这个方法,因为替换系统方法的业务需求只需要执行一次,所以代码中用到的GCDdispatch_once函数

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容