zoukankan      html  css  js  c++  java
  • runtime -- 方法交换的坑自定义方法不执行

    今天在群里看到有人说在viewWillAppear方法里添加埋点的问题

    为了降低代码耦合度,我就觉得可以用runtime的方法交换来实现

    controller里的代码

    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    -(void)viewWillAppear:(BOOL)animated{
        [super viewWillAppear:animated];
        NSLog(@"2222222222222");
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    
    @end
    

     category里的代码

    #import "UIViewController+NewApear.h"
    #import <objc/message.h>
    
    @implementation UIViewController (NewApear)
    
    
    
    -(void)newAppear:(BOOL)animated{
    
    
        
        [self newAppear:animated];
        
        NSLog(@"my code");
    
    }
    
    +(void)load{
        //交换方法
        
        NSLog(@"333");
    
        SEL originalSelector = @selector(viewWillAppear:);
        SEL swizzledSelector = @selector(newAppear:);
        
        Class class = [self class];
        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);
        }
    }
    
    @end
    

    这里的代码是没问题的,但是我刚开始写demo的时候,在使用viewWillAppear的时候没有写

    [super viewWillAppear:animated];

    导致自定义的方法不执行,所以这个super一定要调用

    
    
  • 相关阅读:
    边长为n的正六边形
    simsimi无限次数api微信公众平台
    仿QQ空间送礼物功能
    asp.net动态输出404
    瀑布流布局并实现自动加载
    微信浏览器的HTTP_USER_AGENT
    AutoIt学习系列:目录
    PDA开发系列:Google地图接口
    WinCE、Windows Mobile GPRS连接类
    PDA开发系列:数据库的选择
  • 原文地址:https://www.cnblogs.com/chebaodaren/p/9101793.html
Copyright © 2011-2022 走看看