iOS runtime 完整消息转发 机制

上一篇我们测试了 备用者消息转发 机制, 也就是 - (id)forwardingTargetForSelector:(SEL)aSelector 

如果我们这个函数返回 nil,  那么就会进入到完整消息转发机制,也就是 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector 函数。

如果没有在这个函数提供处理,那么就会触发 doesNotRecognizedSelector 异常。

具体看代码如下:

@interface Dog : NSObject

-(void) Bark:(NSString *)text;

@end


@implementation Dog

-(void) Bark:(NSString *)text {
    NSLog(@"The Dog is Barking : %@", text);
}

@end

 

@interface Horse : NSObject

-(void) Run:(NSString *)text;

@end


@implementation Horse

-(void) Run:(NSString *)text {
    NSLog(@"The Horse is Runing : %@", text);
}

@end

 

@interface Pig : NSObject

@end


@implementation Pig

+ (BOOL) resolveInstanceMethod:(SEL)sel {
    return NO;
}

- (id)forwardingTargetForSelector:(SEL)aSelector {
    return nil;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    
    NSMethodSignature * superSignature = [super methodSignatureForSelector:aSelector];
    if (superSignature == nil) {
        if (aSelector == @selector(Bark:) || aSelector == @selector(Run:)) {
            return [NSMethodSignature signatureWithObjCTypes:"v@:@"];
        }
        else {
            return nil;
        }
    }
    else {
        return superSignature;
    }
    

    return [super methodSignatureForSelector:aSelector];
}

-(void) forwardInvocation:(NSInvocation *)anInvocation {
    NSLog(@"forwardInvocation");
    
    SEL sel = anInvocation.selector;
    Dog * dog = [[Dog alloc] init];
    Horse * horse = [[Horse alloc] init];
    
    if ([dog respondsToSelector:sel]) {
        [anInvocation invokeWithTarget:dog];
    }
    else if([horse respondsToSelector:sel]) {
        [anInvocation invokeWithTarget:horse];
    }
    else {
        [self doesNotRecognizeSelector:sel];
    }
}


@end

 

 外部调用如下:

-(instancetype) init {
    self = [super init];

    Pig * pig = [[Pig alloc] init];
    [pig performSelector:@selector(Bark:) withObject:@"555"];
    [pig performSelector:@selector(Run:) withObject:@"666"];
    
    return self;
}

 

最终输出如下:

 

可以看到,对Pig 没有实现的不同的方法,可以分别转发给 Dog 和 Horse 来实现。

你可能感兴趣的:(iphone/object-c)