消息转发机制

#import 
#import "Airplane.h"
#import "People.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        
        People *tom = [People new];
        //向tom发送fly消息,由于People类中没有实现该方法,会进行消息转发机制
        [(id)tom fly];
        
        
    }
    return 0;
}
#import 

@interface People : NSObject
-(void)fly;
@end
#import 
#import "People.h"
#import "Airplane.h"

void dyMethod(){
    printf("hello world \r\n");
}

@implementation People

//消息转发第一步,动态方法解析
+(BOOL)resolveInstanceMethod:(SEL)sel
{
    if (sel == @selector(fly)) {
        //给类添加方法
        class_addMethod([self class], sel, (IMP)dyMethod, "v@:");
    return YES;
    }
    
    return [super resolveInstanceMethod:sel];
}

//消息转发第二步
-(id)forwardingTargetForSelector:(SEL)aSelector
{
    if (aSelector == @selector(fly))
    {
        //转发给其他target处理fly消息
        return [Airplane new];
    }
    
    return [super forwardingTargetForSelector:aSelector];
}

//消息转发第三步
-(void)forwardInvocation:(NSInvocation *)anInvocation
{
    SEL sel = anInvocation.selector;
    if (sel == @selector(fly))
    {
        //生成新的对象处理fly消息
        Airplane *animal = [Airplane new];
        [anInvocation invokeWithTarget:animal];
    }
}
//先调用方法签名函数,再进入forwardInvocation
-(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    if (aSelector == @selector(fly)) {
        return [NSMethodSignature signatureWithObjCTypes:"v@:"];
    }
    
    return nil;
}

@end
#import 

@interface Airplane : NSObject

-(void)fly;

@end

#import "Airplane.h"

@implementation Airplane

-(void)fly
{
    NSLog(@"Animal fly");
}

@end

你可能感兴趣的:(消息转发机制)