在 iOS中可以直接调用 某个对象的消息 方式有2种
一种是performSelector:withObject:
再一种就是NSInvocation, invocation英文单词就是调用的意思
第一种方式比较简单,能完成简单的调用。但是对于>2个的参数或者有返回值的处理,那就需要做些额外工作才能搞定。那么在这种情况下,我们就可以使用NSInvocation来进行这些相对复杂的操作
NSInvocation可以处理参数、返回值。会java的人都知道反射操作,其实NSInvocation就相当于反射操作。
下面这个例子描述了如何使用NSInvocation,以下例子中如果要正常运行,需要把不存在的类进行正确填写。
SEL subStringSel = @selector(substringFromIndex:);
//初始化NSMethodSignature对象
NSMethodSignature *methodSignature = [[NSString class] instanceMethodSignatureForSelector:subStringSel];
//初始化NSInvocation对象
NSInvocation *myInvocation = [NSInvocation invocationWithMethodSignature:methodSignature];
//设置target
[myInvocation setTarget:string];
//设置selector
[myInvocation setSelector:subStringSel];
//设置参数
int arg1 = 2;
[myInvocation setArgument:&arg1 atIndex:2];//参数从2开始,index 为0表示target,1为_cmd
//获取结果
NSString *resultString = nil;
[myInvocation invoke];
[myInvocation getReturnValue:&resultString];
NSLog(@"2=%@",resultString);
- (void)testClassMethod{
NSString *string = nil;
//初始化NSMethodSignature对象
NSMethodSignature *sig = [NSString methodSignatureForSelector:@selector(stringWithString:)];
//初始化NSInvocation对象
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
//设置执行目标对象
[invocation setTarget:[NSString class]];
//设置执行的selector
[invocation setSelector:@selector(stringWithString:)];
//设置参数
NSString *argString = @"test method";
[invocation setArgument:&argString atIndex:2];
//执行方法
[invocation retainArguments];
[invocation invoke];
//获取返回值
[invocation getReturnValue:&string];
NSLog(@"执行结果 ====%@",string);
}