现在的位置: 首页 > 综合 > 正文

NSMethodSignature和NSInvocation的使用

2013年11月11日 ⁄ 综合 ⁄ 共 1550字 ⁄ 字号 评论关闭

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

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

    //设置target
    [invocation setTarget:self];
    //设置selector
    [invocation setSelector:selector];
    NSString *returnValue = nil;
    NSString *argument1 = @"fist";
    NSNumber *argument2 = [NSNumber numberWithInt:102];
    //设置参数,第一个参数index为2
    [invocation setArgument:&argument1 atIndex:2];
    [invocation setArgument:&argument2 atIndex:3];
    //retain一遍参数
    [invocation retainArguments];
    //调用
    [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]

抱歉!评论已关闭.