第四章 Runtime应用:方法添加

方法添加

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

番薯大佬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值