消息转发机制

#import <Foundation/Foundation.h>
#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 <Foundation/Foundation.h>

@interface People : NSObject
-(void)fly;
@end
#import <objc/runtime.h>
#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 <Foundation/Foundation.h>

@interface Airplane : NSObject

-(void)fly;

@end

#import "Airplane.h"

@implementation Airplane

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

@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容