RunTime运行时之动态替换和改变方法实现

2017-06-07  本文已影响0人  飘金
#import "ViewController.h"
#import <objc/runtime.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //获取方法所有名
    [self getMethodName];
    //添加方法
    [self addMethod];
    //替换方法
    [self changeMethod];
    //改变方法实现
    [self changeMethodImpl];
    //方法实现改变后调用实验
    [self method_1];
}

#pragma 获取方法名
- (void)getMethodName{
    void (*useMethod)(id,SEL);
    unsigned int outCount = 0;
    Method *methods = class_copyMethodList([self class], &outCount);
    for(int i = 0;i < outCount;i++){
        Method method = methods[i];
        SEL sel = method_getName(method);
        NSLog(@"%s",sel_getName(sel));
        if(sel == @selector(method_1)){
            useMethod = (void (*)(id,SEL))[self methodForSelector:sel];
            useMethod(self,sel);
        }
    }
}

#pragma 添加方法
- (void)addMethod{
    class_addMethod([self class], @selector(method::), (IMP)method_impl, "i@:i@");
    //此时调用方法需要用performSelector,否则编译器会报错
    [self performSelector:@selector(method::) withObject:@[@"piaojin",@(25)]];
}

#pragma 动态替换方法(也可以用于替换方法实现)
- (void)changeMethod{
//method_1与method_2进行替换
    method_exchangeImplementations(class_getInstanceMethod([self class], @selector(method_1)), class_getInstanceMethod([self class], @selector(method_2)));
}

#pragma 动态替换方法实现
- (void)changeMethodImpl{
//改变method_1的实现为method_3
    class_replaceMethod([self class], @selector(method_1), (IMP)method_3, "");
}

- (void)method_1{
    NSLog(@"method_1");
}

void method_impl(id self,SEL _cmd,NSString *str,int age){
    NSLog(@"str:%@,age:%d",str,age);
}

- (void)method_2{
    NSLog(@"method_2");
}

void method_3(){
    NSLog(@"method_3");
}

@end
上一篇下一篇

猜你喜欢

热点阅读