在iOS中调用方法的时候超过2两个参数的时候通常使用NSInvocation。
NSInvocation可以处理参数、返回值。
会java的人都知道反射操作,其实NSInvocation就相当于反射操作。
在官方文档中有明确说明,NSInvocation对象只能使用其类方法来初始化,不可使用alloc/init方法。
它执行调用之前,需要设置两个方法:setSelector: 和setArgument:atIndex:
使用示例:
SEL method = @selector(testInvocation);
NSMethodSignature *signature = [[self class] methodSignatureForSelector:@selector(init)];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:self];
[invocation setSelector:method];
[invocation invoke];
- (void)testInvocation
{
NSLog(@"test");
}
SEL method = @selector(testInvocation:);
NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:method];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:self];
[invocation setSelector:method];
int a = 30;
[invocation setArgument:&a atIndex:2];
[invocation retainArguments];
[invocation invoke];
- (void)testInvocation:(int)a
{
NSLog(@"test a");
}
SEL method = @selector(testInvocation:param:);
NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:method];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:self];
[invocation setSelector:method];
int a = 30;
int bb = 20;
[invocation setArgument:&a atIndex:2];
[invocation setArgument:&bb atIndex:3];
[invocation retainArguments];
[invocation invoke];
int d;
[invocation getReturnValue:&d];
NSLog(@“%d",d);
- (int)testInvocation:(int)a param:(int)b
{
NSLog(@"test a + b");
return a + b;
}
结束,以上就是三种示例😄。