动态调用方法时会用到,例子

-(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);

另外一个例子:

SEL selector = @selector(myMethod:setValue2:);

NSMethodSignature *signature = [MyObject instanceMethodSignatureF orSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSign ature:signature];
[invocation setSelector:selector];

NSString *str1 = @"someString";
NSString *str2 = @"someOtherString";

//The invocation object must retain its arguments
[str1 retain];
[str2 retain];

//Set the arguments
[invocation setTarget:targetInstance];
[invocation setArgument:&str1 atIndex:2];
[invocation setArgument:&str2 atIndex:3];

[NSTimer scheduledTimerWithTimeIn terval:0.1 invocation:invocation repeats:YES]