通过运行时调用块,是否类似于NSInvocation? [英] Calling a block though runtime, anything similar to NSInvocation?

查看:98
本文介绍了通过运行时调用块,是否类似于NSInvocation?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个未知类型的块(如id)和需要传递给该块的参数数组.参数可以是包装为NSNumber/NSValue的对象或数字/结构. Block也可能返回对象,数字或结构.这是一个库代码,并且事先不知道参数的类型.

I have block of unknown type (as id) and array of arguments that need to passed into that block. Arguments may be objects or numbers/structs boxed as NSNumber/NSValue. Block may also return an object, number or struct. This is a library code, and types of arguments are not known beforehand.

假设我可以从块描述符中动态读取签名,是否有一种方法可以构造类似于NSInvocation的代码来调用块?

Assuming that I can can dynamically read signature from the block descriptor, is there a way to construct something like an NSInvocation to call a block?

推荐答案

令人惊讶的是:

CGAffineTransform (^block)(id x, int y, CGSize z) = ^(id x, int y, CGSize z){
    NSLog(@"%@,%d,%@", x, y, NSStringFromCGSize(z));
    CGAffineTransform t = { 1, 2, 3, 4, 5, 6 };
    return t;
};

NSMethodSignature* sign = [NSMethodSignature signatureWithObjCTypes:block_signature(block3)];
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:sign];
[invocation setTarget:block3];
void* x = (__bridge void*)@"Foo";
int y = 42;
CGSize z = { 320, 480 };
[invocation setArgument:&x atIndex:1];
[invocation setArgument:&y atIndex:2];
[invocation setArgument:&z atIndex:3];
[invocation invoke];
CGAffineTransform t;
[invocation getReturnValue:&t];

但是,另一方面,这不是:

But on the other hand, this does not:

NSMethodSignature* sign = [self methodSignatureForSelector:@selector(class)];
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:sign];
[invocation setTarget:block];
[invocation setSelector:@selector(class)];
[invocation invoke];
Class k = nil;
[invocation getReturnValue:&k];

反汇编中的AFAICS,[NSInvocation invoke]的实现会检查目标的类,如果它是一个块(NSBlock的子类),那么它总是调用块函数,而与签名无关.

AFAICS from the disassembly, implementation of the [NSInvocation invoke] checks for the class of the target, and if it is a block (subclass of NSBlock) then it always calls block function, regardless of the signature.

已更新:报告为 rdar://25289979

这篇关于通过运行时调用块,是否类似于NSInvocation?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆