runtime-消息转发测试

消息转发forwardingTargetForSelector

#import 

@interface NSCar : NSObject

- (void)run;
+ (void)test;

@end

#import "NSCar.h"

@implementation NSCar

+ (void)test
{
    NSLog(@"%s",__func__);
    
}

- (void)run
{
    
    NSLog(@"%s",__func__);

}

@end

#import "NSPerson.h"
#import "NSCar.h"

@implementation NSPerson
- (id)forwardingTargetForSelector:(SEL)aSelector
{
    if (aSelector == @selector(run)) {
        return [NSCar new];
    }
    return [super forwardingTargetForSelector:aSelector];
}

+ (id)forwardingTargetForSelector:(SEL)aSelector
{
    if (aSelector == @selector(test)) {
        return [NSCar class];
    }
    return [super forwardingTargetForSelector:aSelector];
}




@end

#import 
#import "NSPerson.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSPerson *person = [[NSPerson alloc] init];
        [person run];
        [NSPerson test];
        }
    return 0;
}

//log
2020-08-27 17:14:13.826632+0800 runtime[10740:402889] -[NSCar run]
2020-08-27 17:14:13.827079+0800 runtime[10740:402889] +[NSCar test]
Program ended with exit code: 0

消息转发forwardingTargetForSelector

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    if (aSelector == @selector(run)) {
        return [NSMethodSignature signatureWithObjCTypes:"v16@0:8"];
    }
    return [super methodSignatureForSelector:aSelector];
}


+ (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    if (aSelector == @selector(test)) {
        return [NSMethodSignature signatureWithObjCTypes:"v16@0:8"];
    }
    return [super methodSignatureForSelector:aSelector];
}


- (void)forwardInvocation:(NSInvocation *)anInvocation
{

    
    [anInvocation invokeWithTarget:NSCar.new];
}

+ (void)forwardInvocation:(NSInvocation *)anInvocation
{
    
    
    [anInvocation invokeWithTarget:NSCar.class];
}

//log
2020-08-27 17:29:12.155678+0800 runtime[11021:412709] -[NSCar run]
2020-08-27 17:29:12.156082+0800 runtime[11021:412709] +[NSCar test]
Program ended with exit code: 0

你可能感兴趣的:(runtime-消息转发测试)