强大的NSInvocation

作者: 01_Jack | 来源:发表于2016-01-25 13:39 被阅读6261次

前言

消息转发中提到过NSInvocation这个类,这里说一下我所理解的NSInvocationNSInvocation命令模式的一种实现,它包含选择器、方法签名、相应的参数以及目标对象。所谓的方法签名,即方法所对应的返回值类型和参数类型。当NSInvocation被调用,它会在运行时通过目标对象去寻找对应的方法,从而确保唯一性,可以用[receiver message]来解释。实际开发过程中直接创建NSInvocation的情况不多见,这些事情通常交给系统来做。比如bangJSPatcharm64方法替换的实现就是利用runtime消息转发最后一步中的NSInvocation实现的。

正文

基于这种命令模式,可以利用NSInvocation调用任意SEL甚至block

SEL
- (id)performSelector:(SEL)aSelector withArguments:(NSArray *)arguments {
    
    if (aSelector == nil) return nil;
    NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:aSelector];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    invocation.target = self;
    invocation.selector = aSelector;
    
    // invocation 有2个隐藏参数,所以 argument 从2开始
    if ([arguments isKindOfClass:[NSArray class]]) {
        NSInteger count = MIN(arguments.count, signature.numberOfArguments - 2);
        for (int i = 0; i < count; i++) {
            const char *type = [signature getArgumentTypeAtIndex:2 + i];
            
            // 需要做参数类型判断然后解析成对应类型,这里默认所有参数均为OC对象
            if (strcmp(type, "@") == 0) {
                id argument = arguments[i];
                [invocation setArgument:&argument atIndex:2 + i];
            }
        }
    }
    
    [invocation invoke];
    
    id returnVal;
    if (strcmp(signature.methodReturnType, "@") == 0) {
        [invocation getReturnValue:&returnVal];
    }
    // 需要做返回类型判断。比如返回值为常量需要包装成对象,这里仅以最简单的`@`为例
    return returnVal;
}
运行结果

NSObject中的performSelector相比,没有了参数个数限制。

invocation signature
block
static id invokeBlock(id block ,NSArray *arguments) {
    if (block == nil) return nil;
    id target = [block  copy];

    const char *_Block_signature(void *);
    const char *signature = _Block_signature((__bridge void *)target);

    NSMethodSignature *methodSignature = [NSMethodSignature signatureWithObjCTypes:signature];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
    invocation.target = target;

    // invocation 有1个隐藏参数,所以 argument 从1开始
    if ([arguments isKindOfClass:[NSArray class]]) {
        NSInteger count = MIN(arguments.count, methodSignature.numberOfArguments - 1);
        for (int i = 0; i < count; i++) {
            const char *type = [methodSignature getArgumentTypeAtIndex:1 + i];
            NSString *typeStr = [NSString stringWithUTF8String:type];
            if ([typeStr containsString:@"\""]) {
                type = [typeStr substringToIndex:1].UTF8String;
            }
            
            // 需要做参数类型判断然后解析成对应类型,这里默认所有参数均为OC对象
            if (strcmp(type, "@") == 0) {
                id argument = arguments[i];
                [invocation setArgument:&argument atIndex:1 + i];
            }
        }
    }

    [invocation invoke];

    id returnVal;
    const char *type = methodSignature.methodReturnType;
    NSString *returnType = [NSString stringWithUTF8String:type];
    if ([returnType containsString:@"\""]) {
        type = [returnType substringToIndex:1].UTF8String;
    }
    if (strcmp(type, "@") == 0) {
        [invocation getReturnValue:&returnVal];
    }
    // 需要做返回类型判断。比如返回值为常量需要包装成对象,这里仅以最简单的`@`为例
    return returnVal;
}

运行结果 invocation signature
SEL与block比较
  • invocation
    SEL既有target也有selector,block只有target
  • signature
    SEL有两个隐藏参数,类型均为@ 类型为@: ,分别对应target和selector。block有一个隐藏参数,类型为@?,对应target且block的target为他本身
  • type
    以OC对象为例:SEL的type为@,block的type会跟上具体类型,如@"NSString"
再谈block

在block的invocation中有这样的代码

    const char *_Block_signature(void *);
    const char *signature = _Block_signature((__bridge void *)target);

_Block_signature其实是JavaScriptCore/ObjcRuntimeExtras.h中的私有API(这个头文件并没有公开可以戳这里查看)

既然苹果把API封了,那就自己实现咯,万能的github早有答案CTObjectiveCRuntimeAdditions
CTBlockDescription.hCTBlockDescription.m拖到项目中,代码这样写

static id invokeBlock(id block ,NSArray *arguments) {
    if (block == nil) return nil;
    id target = [block  copy];
    
    CTBlockDescription *ct = [[CTBlockDescription alloc] initWithBlock:target];
    NSMethodSignature *methodSignature = ct.blockSignature;
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
    invocation.target = target;
    
    // invocation 有1个隐藏参数,所以 argument 从1开始
    if ([arguments isKindOfClass:[NSArray class]]) {
        NSInteger count = MIN(arguments.count, methodSignature.numberOfArguments - 1);
        for (int i = 0; i < count; i++) {
            const char *type = [methodSignature getArgumentTypeAtIndex:1 + i];
            NSString *typeStr = [NSString stringWithUTF8String:type];
            if ([typeStr containsString:@"\""]) {
                type = [typeStr substringToIndex:1].UTF8String;
            }
            
            // 需要做参数类型判断然后解析成对应类型,这里默认所有参数均为OC对象
            if (strcmp(type, "@") == 0) {
                id argument = arguments[i];
                [invocation setArgument:&argument atIndex:1 + i];
            }
        }
    }
    
    [invocation invoke];
    
    id returnVal;
    const char *type = methodSignature.methodReturnType;
    NSString *returnType = [NSString stringWithUTF8String:type];
    if ([returnType containsString:@"\""]) {
        type = [returnType substringToIndex:1].UTF8String;
    }
    if (strcmp(type, "@") == 0) {
        [invocation getReturnValue:&returnVal];
    }
    // 需要做返回类型判断。比如返回值为常量需要包装成对象,这里仅以最简单的`@`为例
    return returnVal;
}
运行结果

相关文章

网友评论

  • _顺_1896:我在使用
    id rst = invokeBlock(^(NSString *a, NSString *b){
    return [NSString stringWithFormat:@"%@ ---- and ---- %@ ", a ,b];
    }, @[@"01", @"Jack"]);
    NSLog(@"%@", rst); 时
    打印完成,出现变量被释放空指针异常,程序崩溃,请问博主这种现象如何避免?我尝试使用全局变量来持有返回结果,第一次正常,但是第二次出现同样的被释放的崩溃。
    butterflyer:解决办法。在方法里把returnval加个weak.

    __weak id returnVal;
    const char *type = methodSignature.methodReturnType;
    NSString *returnType = [NSString stringWithUTF8String:type];
  • a5476d6f4c15:方法有两个隐藏参数,分别为self 和cmd 查表type Encoding 就知道是 @: 表示。block也有个隐藏参数,类型为@?,其表示self 和 函数指针 即 IMP。 所以你总结的是错误的
    01_Jack:感谢指正,笔误。cmd对应encoding是 :
  • XIAODAO:看了您的文章,有以下认识:_Block_signature()是iOS的私有API,用来获取一个block的签名的类型编码。请问是否正确?
    NinthDay:// Returns a string describing the block's parameter and return types.
    // The encoding scheme is the same as Objective-C @encode.
    // Returns NULL for blocks compiled with some compilers.
    BLOCK_EXPORT const char * _Block_signature(void *aBlock)

    先声明下 就能用这个函数了

本文标题:强大的NSInvocation

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