runtime——动态添加方法

写在前面:
关于SEL、Method、IMP之前的关系,请参考CornBallast写的Runtime奇技淫巧之类(Class)和对象(id)以及方法(SEL)

动态添加方法

首先新建一个Person类,写eat方法并实现:

#import 
@interface Person : NSObject
- (void)eat;
@end

#import "Person.h"

@implementation Person
- (void)eat {
    NSLog(@"person eat!");
}
@end

我们在VC中#import "Person.h",创建一个Person类的实例someone,让someone调用eat方法:

#import "CSRuntimeDemoVC.h"
#import "Person.h"

@interface CSRuntimeDemoVC ()

@end

@implementation CSRuntimeDemoVC

- (void)viewDidLoad {
    [super viewDidLoad];

    Person *someone = [[Person alloc] init];
    [someone eat];
}
@end

这样显然是没有问题的,因为编译器可以找到Person的实例方法eat和eat方法的实现。
如果我们让someone调用run,objc_msgSend(someone, @selector(run)); 会怎样呢?答案很明显,程序会崩溃。(宝宝才刚学会走,你就要他跑,他能不摔么?)
关于runtime消息发送参考:runtime——消息发送、消息转发

#import "CSRuntimeDemoVC.h"
#import "Person.h"

@interface CSRuntimeDemoVC ()

@end

@implementation CSRuntimeDemoVC

- (void)viewDidLoad {
    [super viewDidLoad];

    Person *someone = [[Person alloc] init];
//    [someone eat];  // 常规调用方法

    // 给someone发送run消息
    objc_msgSend(someone, @selector(run));
}
@end

宝宝还不会走,那我们就教他怎么走路呗,怎么教?
我们动态给Person添加一个实例方法,先来看添加方法的api:

//  添加一个方法到类里面
BOOL class_addMethod ( Class cls, SEL name, IMP imp, const char *types );

参数分析
Class cls 要添加方法的类对象(如果要添加实例方法,传该实例的类对象,如果要添加类方法,传该类的元类)
SEL name 要添加的方法名称生成的SEL
IMP imp 要添加的方法对应的方法实现
const char *types 代表函数类型,比如无参数无返回值 "v@:" ,int类型返回值,一个参数传入"i@:@" ,如果你知道了对应的Method,你可以直接通过method_getTypeEncoding函数获取。

在VC中#import (objc/message.h里包含runtime.h)
在VC中实现personRun方法,然后给Person添加run方法,方法实现指向VC中的personRun:

#import "CSRuntimeDemoVC.h"
#import "Person.h"
#import 

@interface CSRuntimeDemoVC ()

@end

@implementation CSRuntimeDemoVC

- (void)viewDidLoad {
    [super viewDidLoad];

    [self addMethodForPerson];

    Person *someone = [[Person alloc] init];
    objc_msgSend(someone, @selector(run));
}

// 给Person类动态添加实例方法run,run的实现指向personRun
- (void)addMethodForPerson {
    // run方法选择器
    SEL runSel = NSSelectorFromString(@"run");
    // personRun方法实现
    IMP personRunImp = class_getMethodImplementation([self class], @selector(personRun));
    // 函数类型
    const char *types = method_getTypeEncoding(class_getInstanceMethod([self class], @selector(personRun)));
    // 给Person类添加 "run" 方法,方法实现指向 "personRun"
    BOOL addSuccess = class_addMethod([Person class], runSel, personRunImp, types);
    NSLog(@"add method for person %@", addSuccess ? @"success" : @"failure");
}

- (void)personRun {
    NSLog(@"person run");
}

神奇的事情发生了,程序没有崩溃,还执行了personRun方法,说明我们给Person添加方法成功了

[41308:2061333] add method for person success
[41308:2061333] person run

相关api介绍

// 添加方法
BOOL class_addMethod ( Class cls, SEL name, IMP imp, const char *types );
// 获取实例方法
Method class_getInstanceMethod ( Class cls, SEL name );
// 获取类方法
Method class_getClassMethod ( Class cls, SEL name );
// 获取所有方法的List
Method * class_copyMethodList ( Class cls, unsigned int *outCount );
// 替代方法的实现
IMP class_replaceMethod ( Class cls, SEL name, IMP imp, const char *types );
// 返回方法的具体实现
IMP class_getMethodImplementation ( Class cls, SEL name );
IMP class_getMethodImplementation_stret ( Class cls, SEL name );
// 类实例是否响应指定的selector
BOOL class_respondsToSelector ( Class cls, SEL sel );
⚠️:当判断一个实例方法是否实现时,第一个参数要用类对象,也就是[Person class]。
    当判断一个类方法是否实现时,第一个参数要传元类,也就是object_getClass([Person class])。

其中class_addMethod这个方法的实现会覆盖父类的方法实现,但不会取代本类中已存在的实现,如果本类中包含一个同名的实现,则函数会返回NO,即添加方法失败。
如果要修改已存在实现,可以使用class_replaceMethod或者更深一步使用method_setImplementation

你可能感兴趣的:(runtime——动态添加方法)