NSInvocation使用示例

一、概述

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


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


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


二、NSInvocation的使用

1、执行类方法

demo代码如下:

- (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示例代码如下:
- (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);
}


  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值