zoukankan      html  css  js  c++  java
  • Runtime实现对象方法的实现交换

    场景:

    我们有一个"Person"类,有一个对象方法"sayHiWithEnglish",打印输出英文"hello"。我们仍想调用此方法,但想打印中文"你好"。

    怎么办呢?此时,我们需要使用运行时交换两个对象方法的实现即可。

    代码很简单,注释很详细,不再做过多解释。

    // 本类
    
    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject
    
    - (void)sayHiWithEnglish;
    
    @end
    
    #import "Person.h"
    
    @implementation Person
    
    - (void)sayHiWithEnglish{
        NSLog(@"hello");
    }
    
    @end
    // 分类
    
    #import "Person.h"
    
    @interface Person (Extension)
    
    @end
    
    #import "Person+Extension.h"
    #import <objc/runtime.h> // 导入头文件
    
    @implementation Person (Extension)
    
    //当应用启动时,会对项目中所有的类进行一次加载,此时就会调用该方法
    + (void)load{
        
        // 获取老方法
        Method oldM = class_getInstanceMethod([self class], @selector(sayHiWithEnglish));
        // 获取用于交换实现的新方法
        Method newM = class_getInstanceMethod([self class], @selector(sayHiWithChinese));
        
        // 运行时交换两个方法的实现
        method_exchangeImplementations(oldM, newM);
    }
    
    // 当该类被首次使用时调用
    + (void)initialize{
        
    }
    
    // 新方法,用于替换老方法的实现
    - (void)sayHiWithChinese{
        NSLog(@"你好");
    }
    
    @end

    调用:

    - (void)viewDidLoad {
        [super viewDidLoad];
     
        Person *per = [[Person alloc] init];
        [per sayHiWithEnglish];
    }
    
    // 打印输出的是中文“你好”
  • 相关阅读:
    React组件的生命周期
    什么是Mixin
    React的Element的创建和render
    React入门
    Go语言中的map
    Go语言模拟实现简单的区块链
    Go语言中的slice
    Go语言中的struct tag
    spring 与springmvc容器的关系
    SSM Controller 页面之间跳转 重定向,有参 无参问题
  • 原文地址:https://www.cnblogs.com/panda1024/p/6369406.html
Copyright © 2011-2022 走看看