动态调用方法时会用到,例子
-(NSString *)myMethod:(NSString *)param1 withParam2:(NSNumber *)param2
{
NSString *result = @"objc";
NSLog(@"par = %@",param1);
NSLog(@"par 2 = %@",param2);
return result;
}
-(void)invokeMyMethodDynamically
{
SEL selector = @selector(myMethod:withParam2:);
NSMethodSignature *methodSignature = [[self class] instanceMethodSignatureForSelector:selector];//获得类和方法的签名
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
//从签名获得调用对象
[invocation setTarget:self];
//设置target
[invocation setSelector:selector];//设置selector
NSString *returnValue = nil;
NSString *argument1 = @"fist";
NSNumber *argument2 = [NSNumber numberWithInt:102];
[invocation setArgument:&argument1 atIndex:2];//设置参数,第一个参数index为2
[invocation setArgument:&argument2 atIndex:3];
[invocation retainArguments];//retain一遍参数
[invocation invoke];//调用
[invocation getReturnValue:&returnValue];//得到返回值,此时不会再调用,只是返回值
NSLog(@"return value = %@",returnValue);
}