OC消息转发机制

OC消息发送机制: 使用运行时,通过selector 去快速查找IMP(函数指针)的过程。

消息转发:IMP找不到的时候,通过一些方法做转发处理。

#import "Person.h"
#import "Dog.h"
#import "Animal.h"
#import <objc/runtime.h>

@implementation Person

void runNew(id self, SEL sel)
{
    NSLog(@"runNew------执行了");
}

+(BOOL)resolveInstanceMethod:(SEL)sel
{
    
    //在这个方法里可以动态添加一个方法的实现
    if (sel == @selector(run)) {
        class_addMethod(self, sel, (IMP)runNew, "v@:");
    }
    return [super resolveInstanceMethod:sel];
}

- (id)forwardingTargetForSelector:(SEL)aSelector
{
    //在这个方法里做消息分发处理
//    if (aSelector == @selector(run)) {
//        return [[Dog alloc]init];//去执行dog类里的run方法
//    }
//    else if (aSelector == @selector(eat))
//    {
//        return [[Animal alloc]init];//去执行Animal类里的eat方法
//    }
    return [super forwardingTargetForSelector:aSelector];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    return [super forwardInvocation:anInvocation];
}

-(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    if (aSelector == @selector(run)) {
        
        return [NSMethodSignature signatureWithObjCTypes:"v@:"];
    }
    if (aSelector == @selector(eat)) {
        return [NSMethodSignature signatureWithObjCTypes:"v@:"];
    }
    return [NSMethodSignature methodSignatureForSelector:aSelector];
}

-(void)doesNotRecognizeSelector:(SEL)aSelector
{
    //最后, 都没有找到方法实现, 则抛出异常,但程序不会崩溃
    NSLog(@"%@---消息不存在",NSStringFromSelector(aSelector));
}


@end

 

posted on 2019-03-21 20:07  大圣ios博客  阅读(705)  评论(0编辑  收藏  举报