传递与签名不匹配的块参数 [英] Passing block parameter that doesn't match signature

查看:123
本文介绍了传递与签名不匹配的块参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用基于块的API,偶然发现了一个场景,在该场景中,我传入了一个块签名,该签名的签名与该方法所期望的typedef参数不匹配.令我惊讶的是,编译器似乎对此并不关心,并且该应用程序也没有崩溃.这是预期的行为吗?示例:

I'm working with a block-based API and stumbled across a scenario where I was passing in a block parameter that had a signature that didn't match the typedef'd parameter the method was expecting. To my surprise, the compiler didn't seem to care about this, and the app didn't crash. Is this expected behavior? Example:

typedef void(^MyBlock)();
typedef void(^MyBlockWithParam)(id param);

- (void)doWork {
    MyBlockWithParam block1 = ^(id param) {
        NSLog(@"block1: %@", param);
    };

    MyBlock block2 = ^{
        NSLog(@"block2");
    };

    [self loadData:block1];
    [self loadData:block2];
}

- (void)loadData:(MyBlockWithParam)block {
    block(@"foo");
}

推荐答案

提供一个空参数规范,如

Providing an empty arguments specification as in

typedef void(^MyBlock)();

表示未指定"的参数.因此,这两种类型在编写时是兼容的.将第一个声明更改为

means "unspecified" arguments. So the two types are compatible as written. Changing the first declaration to

typedef void(^MyBlock)(void);

指定该块不带任何参数,并且会出现错误.

specifies that the block takes no arguments and you'll get an error.

K& RC指定空的参数列表表示未指定". C块规范说,对于块类型声明,这不正确(请参见. http://clang.llvm.org/docs/BlockLanguageSpec.html#block-variable-declarations )但是:GCC和Clang都将K& R行为实现为语言扩展

K&R C specifies that an empty argument list means "unspecified". The C blocks spec says this is not true for block type declarations (cf. http://clang.llvm.org/docs/BlockLanguageSpec.html#block-variable-declarations) but: both GCC and Clang implement the K&R behavior as a language extension.

这篇关于传递与签名不匹配的块参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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