NSMethodSignature和NSInvocation的使用

本文详细介绍了如何使用Objective-C动态调用方法,并通过实例展示了动态方法调用的实现过程,包括方法签名获取、参数设置及返回值获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

-(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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值