RunTime(消息机制) + RunTime(消息转发)

                                                                 一.消息机制
1.在viewDidLoad中直接用 performSelector:@selector(doSomething) 来调用doSomething方法时,会发现找不到这个方法而奔溃.此时,我们可以在resolveInsantanceMethod:(SEL)see 方法中获取这个所有在运行时阶段的方法,在这个方法中只需要判断一下,将这个方法获取,并且运用Runtime 的 class_addMethod 的方法来将方法和响应函数绑定,进而达到为某一个类添加方法的目的.
- (void)viewDidLoad {
    [superviewDidLoad];
    [selfperformSelector:@selector(doSomething)];
}
//1.对象在收到无法解读的消息后,会调用resolveInstanceMethod
//2.再用class_addMethod 将调用的方法名字和制定函数相关联
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    if (sel == @selector(doSomething)) {
        NSLog(@"add method here");
        class_addMethod([selfclass], sel, (IMP)dynamicMethodIMP, "v@:");
        returnYES;
    }
    return [superresolveInstanceMethod:sel];
}
//函数
void dynamicMethodIMP (idself,SEL_cmd) {
    NSLog(@"doSomething SEL");
}
+ (BOOL)resolveClassMethod:(SEL)sel {
    NSLog(@">> Class resolving %@",NSStringFromSelector(sel));
    return [superresolveClassMethod:sel];
}
                              二.消息转发
#import "ViewController.h"

@interfaceViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [superviewDidLoad];
    [selfperformSelector:@selector(messageViewMethod)];
}

/**
 *  @author zhouyantong
 *
 *  @brief 在这个方法中并没有找到或者实现相应的方法,那么消息会往下传递,在转发方法中看别的界面是否有这个方法
 *
 */
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    return [superresolveInstanceMethod:sel];
}

- (id)forwardingTargetForSelector:(SEL)aSelector {
    Class class = NSClassFromString(@"MessageViewController");
    UIViewController *vc = class.new;
    if (aSelector == NSSelectorFromString(@"messageViewMethod")) {
        NSLog(@"MessageVC do this!");
        return vc;
    }
    returnnil;
}

- (void)didReceiveMemoryWarning {
    [superdidReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
 
 
 
#import "MessageViewController.h"

@interfaceMessageViewController ()

@end

@implementation MessageViewController

- (void)viewDidLoad {
   
}

- (void)messageViewMethod {
    NSLog(@"This is receive method!");
}
@end
 
原文地址:https://www.cnblogs.com/zhouyantongiOSDev/p/5250756.html