小编Yan*_*Yan的帖子

当块的参数数量和类型可以变化时,使用来自va_list的参数调用块

我有一个变量,块接受一些参数.参数的确切数量及其类型可以有所不同.例如,它可以是一个块

void(^testBlock1)(int) = ^(int i){}
Run Code Online (Sandbox Code Playgroud)

或者一个街区

void(^testBlock2)(NSString *,BOOL,int,float) = ^(NSString *str,BOOL b,int i,float f){}
Run Code Online (Sandbox Code Playgroud)

参数类型仅限于{id, BOOL, char, int, unsigned int, float}.

我知道当前的参数数量及其类型.我需要实现一个可以使用给定参数执行块的方法:

-(void)runBlock:(id)block withArguments:(va_list)arguments 
          types:(const char *)types count:(NSUInteger)count;
Run Code Online (Sandbox Code Playgroud)

我有一个天真的解决方案,但它非常难看,只支持不超过4个字节大小的类型并依赖于对齐.所以我正在寻找更好的东西.我的解决方案是这样的:

#define MAX_ARGS_COUNT 5
-(void)runBlock:(id)block withArguments:(va_list)arguments 
          types:(const char *)types count:(NSUInteger)count{

    // We will store arguments in this array.
    void * args_table[MAX_ARGS_COUNT];

    // Filling array with arguments
    for (int i=0; i<count; ++i) {
        switch (types[i]) {
            case '@':
            case 'c':
            case 'i':
            case 'I':
                args_table[i] = (void *)(va_arg(arguments, int));
                break;
            case …
Run Code Online (Sandbox Code Playgroud)

objective-c call ios objective-c-blocks

5
推荐指数
1
解决办法
2045
查看次数

标签 统计

call ×1

ios ×1

objective-c ×1

objective-c-blocks ×1