方法添加
class_addMethod(Class _Nullable cls, SEL _Nonnull name, IMP _Nonnull imp, const char * _Nullable types)
1、cls 被添加方法的类
2、name 添加的方法的名称的SEL
3、imp 方法的实现。该函数必须至少要有两个参数,self,_cmd
4、类型编码
示例class_addMethod([self class], sel, (IMP)fooMethod, "v@:");
代码示例
#import "ViewController.h"
#import "Person.h"
#import "NSMutableArray+RunTime.h"
#import "UIViewController+RunTime.h"
#import "UIView+RunTime.h"
#import <objc/runtime.h>
#import <objc/message.h>
@interface ViewController ()
{
NSMutableArray *names;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.title = @"runtime";
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"click" style:UIBarButtonItemStyleDone target:self action:@selector(buttonClick)];
// 执行work函数
[self performSelector:@selector(work:)];
}
#pragma mark - 消息转发(方法添加)
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
if (sel == @selector(work:))
{
// 如果是执行work函数,就动态解析,指定新的IMP
class_addMethod([self class], sel, (IMP)workMethod, "v@:");
return YES;
}
return [super resolveInstanceMethod:sel];
}
void workMethod(id obj, SEL _cmd)
{
// 新的work函数
NSLog(@"Doing work");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end