美文网首页iOS Developer
NSInvocation的简单使用

NSInvocation的简单使用

作者: liangdahong | 来源:发表于2017-08-17 14:16 被阅读69次

NSInvocation的简单使用

在平时的开发中,可能有这样一个需求,别人给你方法名,给你参数,叫你去执行相应的方法,比如:在OC-JS交互时可能会遇到,那么我们怎么处理呢?我们调用方法最常见的是 [obj func...]; performSelector目前的需求[obj func...];肯定是不行了,performSelector可行但是,它只可以处理不多余2个参数的情况,那么多余2个的怎么处理呢?可能会想到不就是想传多给参数吗?就把参数包装为 NSDictionary 来处理吧,对是一个处理方案。但是现在就是不想用包装的方式。其实用 NSInvocation是可以解决的。(其实是最近有组内有一些小伙伴分享iOS响应链)时接触到的这个类。随便看了下他的使用。

有如下的方法:

- (void)test:(NSString *)a b:(NSString *)b c:(NSString *)c d:(NSString *)d {
    NSLog(@"test: %@, %@, %@, %@", a, b, c, d);
}

现在给你Target 方法名(字符串)参数(数组) 需要你调用此方法

id target = self;
NSString *methodName = @"test:b:c:d:";
NSArray *array = @[@"1", @"22", @"2233", @"c"];

可以如下实现

- (void)testWithTarget:(id)target  SELString:(NSString *)sel parameters:(NSArray *)parameters {
    // 创建SEL
    SEL selector = NSSelectorFromString(sel);
    // 创建NSMethodSignature
    NSMethodSignature *signature = [target methodSignatureForSelector:selector];
    // 创建NSInvocation
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    // 设置target
    invocation.target = target;
    // 设置SEL
    invocation.selector = selector;
    // 增加参数
    [parameters enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [invocation setArgument:&obj atIndex:idx+2];
    }];
    // 开始调用
    [invocation invoke];
}

相关文章

  • 经典开发文章(IOS)

    原文地址: NSInvocation 和 NSMethodSignature的简单使用 http://mobile...

  • NSInvocation的简单使用

    NSInvocation的简单使用 在平时的开发中,可能有这样一个需求,别人给你方法名,给你参数,叫你去执行相应的...

  • NSInvocation的简单使用

    前提: 在 iOS中可以直接调用某个对象的消息方式有两种:一种是performSelector:withObjec...

  • NSMethodSignature与NSInvocation

    NSMethodSignature与NSInvocation简单使用 如果我们只知道一个方法的名称@"test:"...

  • 编码篇 - NSInvocation的简单使用

    前言 在认识 NSInvocation 之前,iOS开发中我们一般会使用以下两种方式去调用一个方法 但是我们知道...

  • NSInvocation个人理解

    NSInvocation的使用: //NSInvocation;用来包装方法和对应的对象,它可以存储方法的名称,对...

  • NSInvocation

    NSInvocation的基本使用 11 异常处理

  • NSInvocation 使用

    NSString*result1 = [selfappend:@"a"withStr2:@"b"andStr3:@...

  • NSInvocation使用

    NSInvocation NSInvocation是一个消息调用类,主要作用是存储和传递消息。它存储的信息包含了一...

  • NSInvocation的使用

    一、介绍 在 iOS中可以直接调用方法的方式有两种: 1、performSelector:withObject;2...

网友评论

    本文标题:NSInvocation的简单使用

    本文链接:https://www.haomeiwen.com/subject/xiogrxtx.html