首页 > 解决方案 > dispatch_block_create - “调用‘dispatch_block_create’没有匹配的函数”

问题描述

我正在尝试在.mm文件中使用 dispatch_block_create 创建一个块

dispatch_block_t testBlock = dispatch_block_create(0, ^{
    NSLog(@"Hello");
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue(), testBlock);
dispatch_block_cancel(testBlock);

Xcode 抱怨:

调用“dispatch_block_create”没有匹配的函数

我什至尝试添加:

#import <dispatch/block.h>

标签: grand-central-dispatchobjective-c++

解决方案


您遗漏了编译器错误的关键部分。我得到:

foo.mm:6:34: error: no matching function for call to 'dispatch_block_create'
    dispatch_block_t testBlock = dispatch_block_create(0, ^{
                                 ^~~~~~~~~~~~~~~~~~~~~
/usr/include/dispatch/block.h:171:1: note: candidate function not viable: no known conversion from 'int' to 'dispatch_block_flags_t' for 1st argument
dispatch_block_create(dispatch_block_flags_t flags, dispatch_block_t block);
^
1 error generated.

关键部分是“候选函数不可行:第一个参数没有从 'int' 到 'dispatch_block_flags_t' 的已知转换”。这是由于 (Objective-)C++ 的类型检查更严格。您需要显式0转换为dispatch_block_flags_t

dispatch_block_t testBlock = dispatch_block_create(static_cast<dispatch_block_flags_t>(0), ^{ ... });

推荐阅读