NSInvocation的使用
在iOS中能够直接调用某个对象的消息。有几种方法:
1. 直接使用该对象进行调用。
2. 能够使用performSelector: withObject;
3. 能够使用NSInvoke来调用。
方法2以及方法3两种方法的差别在于:方法3能够适用于在方法中存在多个參数,以及须要使用该方法的返回值的时候。
使用NSInvoke的方法须要注意:
(1) 传入參数须要从下标2開始,第一个參数用于传入调用的对象
(2) 须要查看返回值类型的时候须要使用NSInvocation中的属性中的methodSignature来获取。
比如:
NSMethodSignature *msg = [[mTestInvoke class] instanceMethodSignatureForSelector:@selector(testInvoke:withArg2:)];
if (msg == nil)
{
NSLog(@"该类没有实现该方法");
return ;
}
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:msg];
// 设置调用制定方法的对象
[invocation setTarget:mTestInvoke];
// 设置第一个參数
int arg1 = 12;
[invocation setArgument:&arg1
atIndex:2];
// 设置第二个參数
int arg2 = 23;
[invocation setArgument:&arg2
atIndex:3];
// 设置须要调用的方法
[invocation setSelector:@selector(testInvoke:withArg2:)];
// 调用方法
[invocation invoke];
// 获取返回值
int returnValue = 0;
[invocation getReturnValue:&returnValue];
// 在这边须要获取返回值的类型
NSLog(@"返回值是 %d, 返回值类型是 %s", returnValue, invocation.methodSignature.methodReturnType);
浙公网安备 33010602011771号