您的位置:首页 > 移动开发 > IOS开发

NSInvocation使用示例 IOS 对象方法的调用 NSInvocation PK performSelector

2016-06-03 07:32 579 查看
http://blog.csdn.net/yhawaii/article/details/8306637

一、概述

在 iOS中可以直接调用 某个对象的消息 方式有2种

第一种方式是使用NSObject类提供的performSelector系列方法

还有一种方式就是使用NSInvocation进行动态运行时的消息分发,动态的执行方法,相信大家一定经常使用NSObject类提供的performSelector系列方法,在这里就不再对此进行描述了,今天主要是分享一下使用NSInvocation动态执行方法。

二、NSInvocation的使用

1、执行类方法

demo代码如下:

[cpp] view
plain copy

- (void)testClassMethod{  

    NSString *string = nil;  

      

    //初始化NSMethodSignature对象  

    NSMethodSignature *sig = [NSString methodSignatureForSelector:@selector(stringWithString:)];  

      

    //初始化NSInvocation对象  

    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];  

      

    //设置执行目标对象  

    [invocation setTarget:[NSString class]];  

      

    //设置执行的selector  

    [invocation setSelector:@selector(stringWithString:)];  

      

    //设置参数  

    NSString *argString = @"test method";  

    [invocation setArgument:&argString atIndex:2];  

      

    //执行方法  

    [invocation retainArguments];  

    [invocation invoke];  

      

    //获取返回值  

    [invocation getReturnValue:&string];  

      

    NSLog(@"执行结果 ====%@",string);  

}  

2、执行实例方法

demo示例代码如下:

[cpp] view
plain copy

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

}  
http://blog.sina.com.cn/s/blog_74e9d98d0101eekc.html
IOS 对象方法的调用  NSInvocation  PK  performSelector

网上有讨论NSInvocation的用法,说某些情况下performSelector不是很方便:


在 iOS中可以直接调用 某个对象的消息 方式有2种

一种是performSelector:withObject:

再一种就是NSInvocation

第一种方式比较简单,能完成简单的调用。但是对于>2个的参数或者有返回值的处理,那就需要做些额外工作才能搞定。那么在这种情况下,我们就可以使用NSInvocation来进行这些相对复杂的操作

个人觉得不以为然,返回值,采用performSelector也能获取返回值,不过返回值都是id类型

对于多个参数的问题,可以采用压箱操作,即把多个参数用NSDictionary 封装成一个对象再传入,这就需要你能随意的修改目标类中的这个方法了,不然也只能采用NSInvocation

地址:http://tiny4cocoa.com/thread-1963-1-1.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: