NSInvocation

声明HZObject

@interface HZObject : NSObject

@end

@implementation HZObject

+ (void)test {
    NSLog(@"HZObject class test");
}

- (void)test {
    NSLog(@"HZObject instance test");
}

+ (void)hzPrintf:(NSString *)string {
    NSLog(@"HZObject class hzPrintf:%@",string);
}

- (void)hzPrintf:(NSString *)string {
    NSLog(@"HZObject instance hzPrintf:%@",string);
}

@end

NSInvocation调用方法

- (void)invocationInvoke:(SEL)selector target:(id)target arguments:(void **)arguments{
    NSMethodSignature *signature = [target methodSignatureForSelector:selector];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    invocation.selector = selector;
    invocation.target = target;
    
    if (arguments != NULL) {
        for (int i = 0; i < 10; i++) {
            void *argument = arguments[i];
            if (argument == NULL) {
                break;
            } else {
                //Indices 0 and 1 indicate the hidden arguments self and _cmd
                //self = target,_cmd =selector
                // Use indices 2 and greater for the arguments normally passed in a message
                [invocation setArgument:argument atIndex:i+2];
            }
        }
    }
    
    [invocation invoke];
}

调用

Class hzObjectClass = [HZObject class];
HZObject *object = [[HZObject alloc] init];

SEL classTest = @selector(test);
SEL instanceTest = @selector(test);
SEL classPrintf = @selector(hzPrintf:);
SEL instancePrintf = @selector(hzPrintf:);

void *arguments[10];

[self invocationInvoke:classTest target:hzObjectClass arguments:arguments];
[self invocationInvoke:instanceTest target:object arguments:arguments];

NSString *classArgument = @"123";
arguments[0] = (void *)&classArgument;

[self invocationInvoke:classPrintf target:hzObjectClass arguments:arguments];
[self invocationInvoke:instancePrintf target:object arguments:arguments];

打印

HZObject class test
HZObject instance test
HZObject class hzPrintf:123
HZObject instance hzPrintf:123

你可能感兴趣的:(NSInvocation)