NSInvocation使用示例
一、概述
在 iOS中可以直接调用 某个对象的消息 方式有2种
还有一种方式就是使用NSInvocation进行动态运行时的消息分发,动态的执行方法,相信大家一定经常使用NSObject类提供的performSelector系列方法,在这里就不再对此进行描述了,今天主要是分享一下使用NSInvocation动态执行方法。
demo代码如下:
- (void)testInstanceMethod{ NSString *string = [NSString stringWithFormat:@"我是一个string"]; NSLog(@"1=%@",string); SEL subStringSel = @selector(substringFromIndex:); //初始化NSMethodSignature对象 NSMethodSignature *methodSignature = [[NSString class] instanceMethodSignatureForSelector:subStringSel]; //初始化NSInvocation对象 NSInvocation *myInvocation = [NSInvocation invocationWithMethodSignature:methodSignature]; //设置target [myInvocation setTarget:string]; //设置selector [myInvocation setSelector:subStringSel]; //设置参数 int arg1 = 2; [myInvocation setArgument:&arg1 atIndex:2];//参数从2开始,index 为0表示target,1为_cmd //获取结果 NSString *resultString = nil; [myInvocation invoke]; [myInvocation getReturnValue:&resultString]; NSLog(@"2=%@",resultString);}